使用DateTime.ToString()格式化日期时是否可以包含日后缀?
例如,我想以下列格式打印日期 - 2009年7月27日星期一。但是,我可以使用DateTime.ToString()查找的最接近的示例是2009年7月27日星期一。
我可以使用DateTime.ToString()执行此操作,还是必须回退到我自己的代码?
答案 0 :(得分:219)
使用开关的另一个选项:
string GetDaySuffix(int day)
{
switch (day)
{
case 1:
case 21:
case 31:
return "st";
case 2:
case 22:
return "nd";
case 3:
case 23:
return "rd";
default:
return "th";
}
}
答案 1 :(得分:53)
作为参考,我总是使用/参考SteveX String Formatting 并且在任何可用变量中似乎没有任何“th”,但您可以使用
轻松构建字符串string.Format("{0:dddd dd}{1} {0:MMMM yyyy}", DateTime.Now, (?));
然后你必须为1提供“st”,为2提供“nd”,为3提供“rd”,为所有其他提供“th”,并且可以用“?:”语句提供。 / p>
var now = DateTime.Now;
(now.Day % 10 == 1 && now.Day != 11) ? "st"
: (now.Day % 10 == 2 && now.Day != 12) ? "nd"
: (now.Day % 10 == 3 && now.Day != 13) ? "rd"
: "th"
答案 2 :(得分:28)
使用几种扩展方法:
namespace System
{
public static class IntegerExtensions
{
public static string ToOccurrenceSuffix(this int integer)
{
switch (integer % 100)
{
case 11:
case 12:
case 13:
return "th";
}
switch (integer % 10)
{
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
}
}
public static class DateTimeExtensions
{
public static string ToString(this DateTime dateTime, string format, bool useExtendedSpecifiers)
{
return dateTime.ToString(format)
.Replace("nn", dateTime.Day.ToOccurrenceSuffix().ToLower())
.Replace("NN", dateTime.Day.ToOccurrenceSuffix().ToUpper());
}
}
}
用法:
return DateTime.Now.ToString("dddd, dnn MMMM yyyy", useExtendedSpecifiers: true);
// Friday, 7th March 2014
注意:整数扩展方法可用于任何数字,而不仅仅是1到31.例如
return 332211.ToOccurrenceSuffix();
// th
答案 3 :(得分:12)
另一种选择是使用Modulo Operator:
public string CreateDateSuffix(DateTime date)
{
// Get day...
var day = date.Day;
// Get day modulo...
var dayModulo = day%10;
// Convert day to string...
var suffix = day.ToString(CultureInfo.InvariantCulture);
// Combine day with correct suffix...
suffix += (day == 11 || day == 12 || day == 13) ? "th" :
(dayModulo == 1) ? "st" :
(dayModulo == 2) ? "nd" :
(dayModulo == 3) ? "rd" :
"th";
// Return result...
return suffix;
}
然后,您可以通过传入 DateTime 对象作为参数来调用上述方法,例如:
// Get date suffix for 'October 8th, 2019':
var suffix = CreateDateSuffix(new DateTime(2019, 10, 8));
有关 DateTime 构造函数的详细信息,请参阅Microsoft Docs Page。
答案 4 :(得分:7)
这是包括第11,12和13位的扩展版本:
DateTime dt = DateTime.Now;
string d2d = dt.ToString("dd").Substring(1);
string daySuffix =
(dt.Day == 11 || dt.Day == 12 || dt.Day == 13) ? "th"
: (d2d == "1") ? "st"
: (d2d == "2") ? "nd"
: (d2d == "3") ? "rd"
: "th";
答案 5 :(得分:5)
更新
NuGet包装:
https://www.nuget.org/packages/DateTimeToStringWithSuffix
例:
https://dotnetfiddle.net/zXQX7y
支持:
.NET Core 1.0及更高版本
.NET Framework 4.5和高级
这是一种扩展方法(因为每个人都喜欢扩展方法),以Lazlow的答案为基础(选择Lazlow的方法很容易阅读)。
与ToString()
上的常规DateTime
方法类似,但如果格式包含d
或dd
,则会自动添加后缀。< / p>
/// <summary>
/// Return a DateTime string with suffix e.g. "st", "nd", "rd", "th"
/// So a format "dd-MMM-yyyy" could return "16th-Jan-2014"
/// </summary>
public static string ToStringWithSuffix(this DateTime dateTime, string format, string suffixPlaceHolder = "$") {
if(format.LastIndexOf("d", StringComparison.Ordinal) == -1 || format.Count(x => x == 'd') > 2) {
return dateTime.ToString(format);
}
string suffix;
switch(dateTime.Day) {
case 1:
case 21:
case 31:
suffix = "st";
break;
case 2:
case 22:
suffix = "nd";
break;
case 3:
case 23:
suffix = "rd";
break;
default:
suffix = "th";
break;
}
var formatWithSuffix = format.Insert(format.LastIndexOf("d", StringComparison.InvariantCultureIgnoreCase) + 1, suffixPlaceHolder);
var date = dateTime.ToString(formatWithSuffix);
return date.Replace(suffixPlaceHolder, suffix);
}
答案 6 :(得分:5)
以@ Lazlow对完整解决方案的回答,以下是完全可重用的扩展方法,并附带示例用法;
internal static string HumanisedDate(this DateTime date)
{
string ordinal;
switch (date.Day)
{
case 1:
case 21:
case 31:
ordinal = "st";
break;
case 2:
case 22:
ordinal = "nd";
break;
case 3:
case 23:
ordinal = "rd";
break;
default:
ordinal = "th";
break;
}
return string.Format("{0:dddd dd}{1} {0:MMMM yyyy}", date, ordinal);
}
要使用它,您只需在DateTime
对象上调用它;
var myDate = DateTime.Now();
var myDateString = myDate.HumanisedFormat()
哪个会给你:
2016年6月17日星期五
答案 7 :(得分:2)
我认为这是一个很好的解决方案,涵盖第111等数字:
private string daySuffix(int day)
{
if (day > 0)
{
if (day % 10 == 1 && day % 100 != 11)
return "st";
else if (day % 10 == 2 && day % 100 != 12)
return "nd";
else if (day % 10 == 3 && day % 100 != 13)
return "rd";
else
return "th";
}
else
return string.Empty;
}
答案 8 :(得分:0)
这里的价值在于我使用以下答案的最终解决方案
DateTime dt = DateTime.Now;
string d2d = dt.ToString("dd").Substring(1);
string suffix =
(dt.Day == 11 || dt.Day == 12 || dt.Day == 13) ? "th"
: (d2d == "1") ? "st"
: (d2d == "2") ? "nd"
: (d2d == "3") ? "rd"
: "th";
Date.Text = DateTime.Today.ToString("dddd d") + suffix + " " + DateTime.Today.ToString("MMMM") + DateTime.Today.ToString(" yyyy");
答案 9 :(得分:0)
string datestring;
// datestring = DateTime.Now.ToString("dd MMMM yyyy"); // 16 January 2021
// code to add 'st' ,'nd', 'rd' and 'th' with day of month
// DateTime todaysDate = DateTime.Now.Date; // enable this line for current date
DateTime todaysDate = DateTime.Parse("01-13-2021"); // custom date to verify code // 13th January 2021
int day = todaysDate.Day;
string dateSuffix;
if(day==1 || day==21 || day==31){
dateSuffix= "st";
}else if(day==2 || day==22 ){
dateSuffix= "nd";
}else if(day==3 || day==23 ){
dateSuffix= "rd";
}else{
dateSuffix= "th";
}
datestring= day+dateSuffix+" "+todaysDate.ToString("MMMM")+" "+todaysDate.ToString("yyyy");
Console.WriteLine(datestring);
答案 10 :(得分:0)
查看humanizr: https://github.com/Humanizr/Humanizer#date-time-to-ordinal-words
new DateTime(2015, 1, 1).ToOrdinalWords() => "1st January 2015"
new DateTime(2015, 2, 12).ToOrdinalWords() => "12th February 2015"
new DateTime(2015, 3, 22).ToOrdinalWords() => "22nd March 2015"
// for English US locale
new DateTime(2015, 1, 1).ToOrdinalWords() => "January 1st, 2015"
new DateTime(2015, 2, 12).ToOrdinalWords() => "February 12th, 2015"
new DateTime(2015, 3, 22).ToOrdinalWords() => "March 22nd, 2015"
发布此消息后,我立即意识到@Gumzle提出了同样的建议,但我错过了他的帖子,因为它被埋在了代码片段中。因此,这是他的答案,其中包含足够的代码,使得像我这样的人可以快速滚动浏览该代码。
答案 11 :(得分:0)
对于那些乐于使用外部依赖关系的人(在这种情况下,使用奇妙的Humanizr .net),就像
一样简单 dateVar.Day.Ordinalize(); \\ 1st, 4th etc depending on the value of dateVar
答案 12 :(得分:0)
获取日期后缀。 (静态功能)
public static string GetSuffix(this string day)
{
string suffix = "th";
if (int.Parse(day) < 11 || int.Parse(day) > 20)
{
day = day.ToCharArray()[day.ToCharArray().Length - 1].ToString();
switch (day)
{
case "1":
suffix = "st";
break;
case "2":
suffix = "nd";
break;
case "3":
suffix = "rd";
break;
}
}
return suffix;
}
答案 13 :(得分:0)
public static String SuffixDate(DateTime date) { string ordinal;
switch (date.Day)
{
case 1:
case 21:
case 31:
ordinal = "st";
break;
case 2:
case 22:
ordinal = "nd";
break;
case 3:
case 23:
ordinal = "rd";
break;
default:
ordinal = "th";
break;
}
if (date.Day < 10)
return string.Format("{0:d}{2} {1:MMMM yyyy}", date.Day, date, ordinal);
else
return string.Format("{0:dd}{1} {0:MMMM yyyy}", date, ordinal);
}
答案 14 :(得分:0)
我是这样做的,它解决了其他例子中给出的一些问题。
public static string TwoLetterSuffix(this DateTime @this)
{
var dayMod10 = @this.Day % 10;
if (dayMod10 > 3 || dayMod10 == 0 || (@this.Day >= 10 && @this.Day <= 19))
{
return "th";
}
else if(dayMod10 == 1)
{
return "st";
}
else if (dayMod10 == 2)
{
return "nd";
}
else
{
return "rd";
}
}
答案 15 :(得分:0)
廉价而开朗的VB解决方案:
litDate.Text = DatePart("dd", Now) & GetDateSuffix(DatePart("dd", Now))
Function GetDateSuffix(ByVal dateIn As Integer) As String
'// returns formatted date suffix
Dim dateSuffix As String = ""
Select Case dateIn
Case 1, 21, 31
dateSuffix = "st"
Case 2, 22
dateSuffix = "nd"
Case 3, 23
dateSuffix = "rd"
Case Else
dateSuffix = "th"
End Select
Return dateSuffix
End Function
答案 16 :(得分:-2)
使用最后一个字符串字符的另一个选项:
public static string getDayWithSuffix(int day) {
string d = day.ToString();
if (day < 11 || day > 13) {
if (d.EndsWith("1")) {
d += "st";
} else if (d.EndsWith("2")) {
d += "nd";
} else if (d.EndsWith("3")) {
d += "rd";
} else {
d += "th";
} else {
d += "th";
}
return d;
}
答案 17 :(得分:-2)
public string CustomToString(this DateTime date)
{
string dateAsString = string.empty;
<here wright your code to convert 17 to 17th>
return dateAsString;
}