获取AM / PM仅使用一个datetime格式的日期和时间以小写日期、格式、时间、AM

2023-09-03 11:51:19 作者:尨浩

我得到一个自定义DateTime格式,包括AM / PM指示,但我想要的AM或PM,以小写的没有的制作小写字符的其余部分。

I'm to get a custom DateTime format including the AM/PM designator, but I want the "AM" or "PM" to be lowercase without making the rest of of the characters lowercase.

这可能使用一个单一的格式,无需使用正则表达式?

Is this possible using a single format and without using a regex?

下面就是我有现在:

item.PostedOn.ToString("dddd, MMMM d, yyyy a\\t h:mmtt")

输出的一个例子,现在是周六,2009年1月31日下午1时34

推荐答案

我会亲自格式化分为两部分:非AM / PM的一部分,和AM / PM的一部分与TOLOWER:

I would personally format it in two parts: the non-am/pm part, and the am/pm part with ToLower:

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

另一种选择(我将探讨在几秒钟之内),就是抓住当前的DateTimeFormatInfo,创建一个副本,并设置了AM / PM指示符的小写版本。然后使用普通格式的格式信息。你想要缓存的DateTimeFormatInfo,显然...

Another option (which I'll investigate in a sec) is to grab the current DateTimeFormatInfo, create a copy, and set the am/pm designators to the lower case version. Then use that format info for the normal formatting. You'd want to cache the DateTimeFormatInfo, obviously...

编辑:尽管我的意见,我写缓存位反正。它可能不会的更快的比code以上(因为它涉及锁和一本字典查询),但它确实让调用code简单:

Despite my comment, I've written the caching bit anyway. It probably won't be faster than the code above (as it involves a lock and a dictionary lookup) but it does make the calling code simpler:

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

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

Here's a complete program to demonstrate:

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