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

Cra*_*vis 74 .net c# date

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

例如,我想以下列格式打印日期 - 2009年7月27日星期一.但是,我可以使用DateTime.ToString()找到的最接近的示例是2009年7月27日星期一.

我可以使用DateTime.ToString()执行此操作,还是我将不得不回到我自己的代码?

Laz*_*low 233

另一种选择使用开关:

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";
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @Lazlow如果你想知道突然的活动:你的答案被[The Daily WTF]的"如何做对"的例子联系起来(http://thedailywtf.com/Articles/Remember,-Remember-the- ThirtyThird-的-November.aspx). (24认同)
  • +1简单易读,最重要的是,适用于所有情况. (10认同)

Bry*_*che 59

作为参考,我总是使用/引用SteveX字符串格式, 并且在任何可用变量中似乎没有任何"th",但您可以轻松地构建一个字符串

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

然后你必须为1提供"st",为2提供"nd",为3提供"rd",为所有其他提供"th",并且可以使用"?:"语句.

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"
Run Code Online (Sandbox Code Playgroud)

  • 这需要进一步扩展以涵盖其他情况,否则你最终会得到"21th",例如. (22认同)
  • 在同一个表达式中多次检索`DateTime.Now`,如果代码在午夜左右执行,则值可以不同. (8认同)
  • 这应该可以完美地解决您的问题 (2认同)
  • @Jez我认为没有超过100的日期,请检查Microsoft Doc https://learn.microsoft.com/en-us/dotnet/api/system.datetime.day 答案的上一个编辑必须是正确的: https://stackoverflow.com/revisions/2050854/4 并重新返回您的更改 (2认同)

Oun*_*ess 30

使用几种扩展方法:

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 useExtendedSpecifiers 
                ? dateTime.ToString(format)
                    .Replace("nn", dateTime.Day.ToOccurrenceSuffix().ToLower())
                    .Replace("NN", dateTime.Day.ToOccurrenceSuffix().ToUpper())
                : dateTime.ToString(format);
        } 
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

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

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

return 332211.ToOccurrenceSuffix();
// th
Run Code Online (Sandbox Code Playgroud)

  • 你的代码类...忘记检查`useExtendedSpecifiers`布尔值:p (6认同)
  • 最优雅的解决方案。这正是扩展方法的设计目的。已添加到我不断增长的扩展方法库中,谢谢! (2认同)

Ant*_*lsh 12

另一个选择是使用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;
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以通过将DateTime对象作为参数传入来调用上述方法,例如:

// Get date suffix for 'October 8th, 2019':
var suffix = CreateDateSuffix(new DateTime(2019, 10, 8));
Run Code Online (Sandbox Code Playgroud)

有关DateTime构造函数的更多信息,请参阅Microsoft Docs页面.

  • @Greg奇怪的是`var suffix = CreateDateSuffix(new DateTime(2013,10,8));`在我的情况下返回'8th'? (2认同)

Pio*_*ski 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";
Run Code Online (Sandbox Code Playgroud)


Mar*_*per 6

以@ 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);
} 
Run Code Online (Sandbox Code Playgroud)

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

var myDate = DateTime.Now();
var myDateString = myDate.HumanisedFormat()
Run Code Online (Sandbox Code Playgroud)

哪个会给你:

2016年6月17日星期五


GFo*_*y83 5

更新

NuGet程序包:https :
//www.nuget.org/packages/DateTimeToStringWithSuffix

示例:https
//dotnetfiddle.net/zXQX7y

支持:
.NET Core 1.0和更高版本
.NET Framework 4.5和更高版本


这是一个扩展方法(因为每个人都喜欢扩展方法),并以Lazlow的答案为基础(因为易于阅读,所以选择了Lazlow的答案)。

与常规ToString()方法的工作原理相同DateTime,不同之处在于,如果格式包含ddd,则后缀将自动添加。

/// <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);
}
Run Code Online (Sandbox Code Playgroud)