使用DateTime.ToString()时获取日后缀

时间:2022-03-16 21:51:38

Is it possible to include the day suffix when formatting a date using DateTime.ToString()?

在使用DateTime.ToString()格式化日期时,是否可以包含day后缀?

For example I would like to print the date in the following format - Monday 27th July 2009. However the closest example I can find using DateTime.ToString() is Monday 27 July 2009.

例如,我想用以下格式打印日期——2009年7月27日星期一。然而,使用DateTime.ToString()我能找到的最接近的示例是2009年7月27日星期一。

Can I do this with DateTime.ToString() or am I going to have to fall back to my own code?

我可以使用DateTime.ToString()来实现这一点,还是必须回到我自己的代码中?

15 个解决方案

#1


49  

As a reference I always use/refer to SteveX String Formatting and there doesn't appear to be any "th" in any of the available variables but you could easily build a string with

作为引用,我总是使用/引用SteveX字符串格式,在任何可用的变量中似乎都没有任何“th”,但是您可以使用它轻松构建一个字符串

string.Format("{0:dddd dd}{1} {0:MMMM yyyy}", DateTime.Now, (?));

You would then have to supply a "st" for 1, "nd" for 2, "rd" for 3, and "th" for all others and could be in-lined with a "? :" statement.

然后,你需要为1,“nd”提供一个“st”,“rd”为3,“th”为所有其他的,并且可以是in-line with a“?”:“声明。

(DateTime.Now.Day % 10 == 1 && DateTime.Now.Day != 11) ? "st"
: (DateTime.Now.Day % 10 == 2 && DateTime.Now.Day != 12) ? "nd"
: (DateTime.Now.Day % 10 == 3 && DateTime.Now.Day != 13) ? "rd"
: "th"

#2


200  

Another option using switch:

另一个选择使用开关:

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";
    }
}

#3


21  

Using a couple of extension methods:

使用一些扩展方法:

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());
        } 
    }
}

Usage:

用法:

return DateTime.Now.ToString("dddd, dnn MMMM yyyy", useExtendedSpecifiers: true);
// Friday, 7th March 2014

Note: The integer extension method can be used for any number, not just 1 to 31. e.g.

注意:整数扩展方法可以用于任何数字,而不仅仅是1到31。如。

return 332211.ToOccurrenceSuffix();
// th

#4


12  

Another option is using the Modulo Operator:

另一种选择是使用Modulo操作符:

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;
}

#5


7  

Here is extended version including 11th, 12th and 13th:

以下是扩展版,包括第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";

#6


4  

Here's an extension method (because everyone loves extension methods), with Lazlow's answer as the basis (picked Lazlow's as it's easy to read).

这里有一个扩展方法(因为每个人都喜欢扩展方法),使用Lazlow的答案作为基础(选择Lazlow的答案是因为它易于阅读)。

Works just like the regular ToString() method on DateTime with the exception that if the format contains a d or dd, then the suffix will be added automatically.

它的工作方式与DateTime上的常规ToString()方法类似,但是如果格式包含d或dd,则会自动添加后缀。

/// <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);
}

#7


4  

Taking @Lazlow's answer to a complete solution, the following is a fully reusable extension method, with example usage;

使用@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);
} 

To use this you would simply call it on a DateTime object;

要使用它,只需在DateTime对象上调用它;

var myDate = DateTime.Now();
var myDateString = myDate.HumanisedFormat()

Which will give you:

这将给你:

Friday 17th June 2016

2016年6月17日星期五

#8


2  

I believe this to be a good solution, covering numbers such as 111th etc:

我认为这是一个很好的解决方案,包括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;
}

#9


0  

I did it like this, it gets around some of the problems given in the other examples.

我这样做,它避开了其他例子中给出的一些问题。

    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";
        }
    }

#10


0  

A cheap and cheerful VB solution:

一个廉价而令人愉快的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

#11


0  

For what its worth here is my final solution using the below answers

下面是我最后的答案

     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"); 

#12


0  

public static String SuffixDate(DateTime date) { string ordinal;

公共静态字符串后缀(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);
  }

#13


0  

Get Date Suffix. (Static Function)

获取日期后缀。(静态函数)

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;
}

Reference: https://www.aspsnippets.com/Articles/Display-st-nd-rd-and-th-suffix-after-day-numbers-in-Formatted-Dates-using-C-and-VBNet.aspx

参考:https://www.aspsnippets.com/Articles/Display-st-nd-rd-and-th-suffix-after-day-numbers-in-Formatted-Dates-using-C-and-VBNet.aspx

#14


-1  

in the MSDN documentation there is no reference to a culture that could convert that 17 into 17th. so You should do it manually via code-behind.Or build one...you could build a function that does that.

在MSDN文档中,没有提到可以将17转换为17的文化。因此,您应该通过代码后手动完成它。或者建立一个……你可以建立一个这样的函数。

public string CustomToString(this DateTime date)
    {
        string dateAsString = string.empty;
        <here wright your code to convert 17 to 17th>
        return dateAsString;
    }

#15


-1  

Another option using the last string character:

使用最后一个字符串字符的另一个选项:

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;
}

#1


49  

As a reference I always use/refer to SteveX String Formatting and there doesn't appear to be any "th" in any of the available variables but you could easily build a string with

作为引用,我总是使用/引用SteveX字符串格式,在任何可用的变量中似乎都没有任何“th”,但是您可以使用它轻松构建一个字符串

string.Format("{0:dddd dd}{1} {0:MMMM yyyy}", DateTime.Now, (?));

You would then have to supply a "st" for 1, "nd" for 2, "rd" for 3, and "th" for all others and could be in-lined with a "? :" statement.

然后,你需要为1,“nd”提供一个“st”,“rd”为3,“th”为所有其他的,并且可以是in-line with a“?”:“声明。

(DateTime.Now.Day % 10 == 1 && DateTime.Now.Day != 11) ? "st"
: (DateTime.Now.Day % 10 == 2 && DateTime.Now.Day != 12) ? "nd"
: (DateTime.Now.Day % 10 == 3 && DateTime.Now.Day != 13) ? "rd"
: "th"

#2


200  

Another option using switch:

另一个选择使用开关:

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";
    }
}

#3


21  

Using a couple of extension methods:

使用一些扩展方法:

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());
        } 
    }
}

Usage:

用法:

return DateTime.Now.ToString("dddd, dnn MMMM yyyy", useExtendedSpecifiers: true);
// Friday, 7th March 2014

Note: The integer extension method can be used for any number, not just 1 to 31. e.g.

注意:整数扩展方法可以用于任何数字,而不仅仅是1到31。如。

return 332211.ToOccurrenceSuffix();
// th

#4


12  

Another option is using the Modulo Operator:

另一种选择是使用Modulo操作符:

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;
}

#5


7  

Here is extended version including 11th, 12th and 13th:

以下是扩展版,包括第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";

#6


4  

Here's an extension method (because everyone loves extension methods), with Lazlow's answer as the basis (picked Lazlow's as it's easy to read).

这里有一个扩展方法(因为每个人都喜欢扩展方法),使用Lazlow的答案作为基础(选择Lazlow的答案是因为它易于阅读)。

Works just like the regular ToString() method on DateTime with the exception that if the format contains a d or dd, then the suffix will be added automatically.

它的工作方式与DateTime上的常规ToString()方法类似,但是如果格式包含d或dd,则会自动添加后缀。

/// <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);
}

#7


4  

Taking @Lazlow's answer to a complete solution, the following is a fully reusable extension method, with example usage;

使用@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);
} 

To use this you would simply call it on a DateTime object;

要使用它,只需在DateTime对象上调用它;

var myDate = DateTime.Now();
var myDateString = myDate.HumanisedFormat()

Which will give you:

这将给你:

Friday 17th June 2016

2016年6月17日星期五

#8


2  

I believe this to be a good solution, covering numbers such as 111th etc:

我认为这是一个很好的解决方案,包括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;
}

#9


0  

I did it like this, it gets around some of the problems given in the other examples.

我这样做,它避开了其他例子中给出的一些问题。

    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";
        }
    }

#10


0  

A cheap and cheerful VB solution:

一个廉价而令人愉快的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

#11


0  

For what its worth here is my final solution using the below answers

下面是我最后的答案

     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"); 

#12


0  

public static String SuffixDate(DateTime date) { string ordinal;

公共静态字符串后缀(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);
  }

#13


0  

Get Date Suffix. (Static Function)

获取日期后缀。(静态函数)

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;
}

Reference: https://www.aspsnippets.com/Articles/Display-st-nd-rd-and-th-suffix-after-day-numbers-in-Formatted-Dates-using-C-and-VBNet.aspx

参考:https://www.aspsnippets.com/Articles/Display-st-nd-rd-and-th-suffix-after-day-numbers-in-Formatted-Dates-using-C-and-VBNet.aspx

#14


-1  

in the MSDN documentation there is no reference to a culture that could convert that 17 into 17th. so You should do it manually via code-behind.Or build one...you could build a function that does that.

在MSDN文档中,没有提到可以将17转换为17的文化。因此,您应该通过代码后手动完成它。或者建立一个……你可以建立一个这样的函数。

public string CustomToString(this DateTime date)
    {
        string dateAsString = string.empty;
        <here wright your code to convert 17 to 17th>
        return dateAsString;
    }

#15


-1  

Another option using the last string character:

使用最后一个字符串字符的另一个选项:

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;
}