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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2050805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:01:10  来源:igfitidea点击:

Getting day suffix when using DateTime.ToString()

c#.netdate

提问by Craig Bovis

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

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

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() 来做到这一点还是我将不得不退回到我自己的代码?

采纳答案by Bryan Bailliache

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

作为参考,我总是使用/引用SteveX String Formatting并且在任何可用变量中似乎都没有任何“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 提供“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"

回答by GxG

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

回答by Piotr Lewandowski

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

回答by Anthony Walsh

Another option is using the 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;
}

You would then call the above method by passing-in a DateTimeobject as a parameter, for example:

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

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

For more info about the DateTimeconstructor, please see Microsoft Docs Page.

有关DateTime构造函数的详细信息,请参阅Microsoft Docs 页

回答by Lazlow

Another option using switch:

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

回答by Jodda

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

回答by Duncan

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

我相信这是一个很好的解决方案,涵盖诸如 111th 等数字:

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

回答by Tony

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

回答by rashleighp

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

回答by Corbin Spicer

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