【问题标题】:What is date format for 07th November 2021?2021 年 11 月 7 日的日期格式是什么?
【发布时间】:2022-01-12 11:04:23
【问题描述】:

我想要日期格式为 2021 年 11 月 7 日。请告诉我格式。

提前致谢。

【问题讨论】:

  • 看起来像自定义日期格式,th 部分我不知道,但其余部分应该很简单。检查Custom date and time format strings
  • 您必须将“第 1 天”、“第 2 天”和“第 3 天”进行特殊处理,持续时间 > 3 天:“dd'th' MMMM yyyy”
  • @SᴇM 非常接近,但这将匹配 07 而不是 07th
  • 您已经获得了出色的服务/迅速的答案。您是否要考虑对答案进行投票并接受答案。

标签: c# .net


【解决方案1】:

棘手的部分是“th”,因为它必须在一个月的某些日子里变异为“st”/“nd”/“rd”。

所以现在需要这个序数后缀的特殊情况,例如:

string ordinalSuffix;
if (date.Day == 1 || date.Day == 21 || date.Day == 31)
    ordinalSuffix = "st";
else if (date.Day == 2 || date.Day == 22)
    ordinalSuffix = "nd";
else if (date.Day == 3 || date.Day == 23)
    ordinalSuffix = "rd";
else
    ordinalSuffix= "th";

string formatted = date.ToString($"dd'{ordinalSuffix}' MMMM yyyy");

您肯定知道这仅适用于英语。要支持其他语言,您可以考虑使用像 Humanizer 这样的库。

【讨论】:

  • 21、22、23、30、31 怎么样?
  • 我会将st/nd/rd/th 存储在一个变量中,然后再执行ToString,以避免重复MMMM yyyy
  • @phuzi 很好,已编辑
  • 正如@Cleptus 所说,我会尝试减少它,以便只有一个date.ToString() 使用变量来存储后缀。
  • 感谢改进建议,编辑了答案。
【解决方案2】:

在这里尝试使用这个功能:

        public static string ToStringWithSuffix(this DateTime dt, string format) {   
        // The format parameter MUST contain [$suffix] within it, which will be replaced.   
        int day = dt.Day; string suffix = "";   
        // Exception for the 11th, 12th, & 13th   
        // (which would otherwise end up as 11st, 12nd, 13rd)   
        if (day % 100 >= 11 && day % 100 <= 13) {   
            suffix = "th";   
        }else{
            switch (day % 10) {   
                case 1: 
                    suffix = "st";   
                    break;   
                case 2:
                    suffix = "nd";   
                    break;   
                case 3:   
                    suffix = "rd";   
                    break;  
                default:   
                    suffix = "th";   
                    break;   
            }
        }
        // Convert the date to the format required, then add the suffix.   
    return dt.ToString(format).replace("[$suffix]",suffix);
}

你可以这样称呼它:

DateTime(2021, 2, 21);
Console.WriteLine(dt.ToStringWithSuffix("dd'[$suffix]' MMMM yyyy"));

如果您需要其他格式,也可以查看Custom date and time format strings 上的文档。

来源:https://gist.github.com/woodss/006f28f01dcf371c2bd1

【讨论】:

  • 我喜欢你的逻辑,但请考虑添加一个示例调用,例如 DateTime dt = new DateTime(2021, 2, 21); Console.WriteLine(dt.ToStringWithSuffix("dd[$suffix] MMMM yyyy"));
  • 感谢您的建议。我会考虑你的建议,我会编辑我的答案!
猜你喜欢
  • 2014-11-25
  • 2012-06-18
  • 2023-03-05
  • 1970-01-01
  • 2015-04-29
  • 1970-01-01
  • 2022-11-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多