仅使用日期时间格式以小写形式获取AM/PM的日期时间

Dan*_*fer 48 .net datetime string-formatting

我将获得一个自定义DateTime格式,包括AM/PM指示符,但我希望"AM"或"PM"为小写而不使其余的字符小写.

这可能使用单一格式而不使用正则表达式吗?

这就是我现在所拥有的:

item.PostedOn.ToString("dddd, MMMM d, yyyy a\\t h:mmtt")
Run Code Online (Sandbox Code Playgroud)

现在输出的一个例子是2009年1月31日星期六下午1:34

Jon*_*eet 61

我个人将它格式化为两部分:非上午/下午部分,以及带有ToLower的上午/下午部分:

string formatted = item.PostedOn.ToString("dddd, MMMM d, yyyy a\\t h:mm") +
                   item.PostedOn.ToString("tt").ToLower();
Run Code Online (Sandbox Code Playgroud)

另一个选项(我将在一秒内调查)是获取当前的DateTimeFormatInfo,创建一个副本,并将am/pm指示符设置为小写版本.然后使用该格式信息进行常规格式化.你想要缓存DateTimeFormatInfo,显然......

编辑:尽管我的评论,我还是编写了缓存位.它可能不会比上面的代码更快(因为它涉及锁和字典查找)但它确实使调用代码更简单:

string formatted = item.PostedOn.ToString("dddd, MMMM d, yyyy a\\t h:mmtt",
                                          GetLowerCaseInfo());
Run Code Online (Sandbox Code Playgroud)

这是一个完整的程序来演示:

using System;
using System.Collections.Generic;
using System.Globalization;

public class Test
{
    static void Main()
    {
        Console.WriteLine(DateTime.Now.ToString("dddd, MMMM d, yyyy a\\t h:mmtt",
                                                GetLowerCaseInfo());
    }

    private static readonly Dictionary<DateTimeFormatInfo,DateTimeFormatInfo> cache =
        new Dictionary<DateTimeFormatInfo,DateTimeFormatInfo>();

    private static object cacheLock = new object();

    public static DateTimeFormatInfo GetLowerCaseInfo()
    {
        DateTimeFormatInfo current = CultureInfo.CurrentCulture.DateTimeFormat;
        lock (cacheLock)
        {
            DateTimeFormatInfo ret;
            if (!cache.TryGetValue(current, out ret))
            {
                ret = (DateTimeFormatInfo) current.Clone();
                ret.AMDesignator = ret.AMDesignator.ToLower();
                ret.PMDesignator = ret.PMDesignator.ToLower();
                cache[current] = ret;
            }
            return ret;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


cas*_*One 20

您可以将格式字符串拆分为两部分,然后将AM/PM部分小写,如下所示:

DateTime now = DateTime.Now;
string nowString = now.ToString("dddd, MMMM d, yyyy a\\t h:mm");
nowString = nowString + now.ToString("tt").ToLower();
Run Code Online (Sandbox Code Playgroud)

但是,我认为更优雅的解决方案是使用您构造的DateTimeFormatInfo实例并分别用"am"和"pm" 替换AMDesignatorPMDesignator属性:

DateTimeFormatInfo fi = new DateTimeFormatInfo();

fi.AMDesignator = "am";
fi.PMDesignator = "pm";

string nowString = now.ToString("dddd, MMMM d, yyyy a\\t h:mmtt", fi);
Run Code Online (Sandbox Code Playgroud)

您可以使用该DateTimeFormatInfo实例来自定义将a转换DateTime为a的许多其他方面string.

  • 或者简单地 `now.ToString("dddd, MMMM d, yyyy a\\th:mmtt", new DateTimeFormatInfo { AMDesignator = "am", PMDesignator = "pm" });` (2认同)