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

发布于 2024-07-12 05:16:28 字数 262 浏览 7 评论 0原文

我要获取包含 AM/PM 指示符的自定义日期时间格式,但我希望“AM”或“PM”为小写而不使其余字符小写。

是否可以使用单一格式而不使用正则表达式?

这是我现在得到的:

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

现在的输出示例为2009 年 1 月 31 日星期六下午 1:34

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?

Here's what I've got right now:

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

An example of the output right now would be Saturday, January 31, 2009 at 1:34PM

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

迷途知返 2024-07-19 05:16:28

我个人会将其格式化为两部分:非 am/pm 部分和使用 ToLower 的 am/pm 部分:

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

另一个选项(我将立即研究)是获取当前的 DateTimeFormatInfo,创建一个副本,然后将 am/pm 指示符设置为小写版本。 然后使用该格式信息进行正常格式化。 显然,您想要缓存 DateTimeFormatInfo...

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

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

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

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

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

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...

EDIT: 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;
        }
    }
}
野稚 2024-07-19 05:16:28

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

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

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

DateTimeFormatInfo fi = new DateTimeFormatInfo();

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

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

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

You could split the format string into two parts, and then lowercase the AM/PM part, like so:

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

However, I think the more elegant solution is to use a DateTimeFormatInfo instance that you construct and replace the AMDesignator and PMDesignator properties with "am" and "pm" respectively:

DateTimeFormatInfo fi = new DateTimeFormatInfo();

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

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

You can use the DateTimeFormatInfo instance to customize many other aspects of transforming a DateTime to a string.

决绝 2024-07-19 05:16:28

编辑:乔恩的示例要好得多,尽管我认为扩展方法仍然是可行的方法,因此您不必到处重复代码。 我已经删除了替换并替换了扩展方法中 Jon 的第一个示例。 我的应用程序通常是 Intranet 应用程序,我不必担心非美国文化。

添加一个扩展方法来为您执行此操作。

public static class DateTimeExtensions
{
    public static string MyDateFormat( this DateTime dateTime )
    {
       return dateTime.ToString("dddd, MMMM d, yyyy a\\t h:mm") +
              dateTime.ToString("tt").ToLower();
    }
}

...

item.PostedOn.MyDateFormat();

编辑:有关如何执行此操作的其他想法,请访问如何在 C# 中格式化日期时间,例如“2008 年 10 月 10 日 10:43am CST”

EDIT: Jon's example is much better, though I think the extension method is still the way to go so you don't have to repeat the code everywhere. I've removed the replace and substituted Jon's first example in place in the extension method. My apps are typically intranet apps and I don't have to worry about non-US cultures.

Add an extension method to do this for you.

public static class DateTimeExtensions
{
    public static string MyDateFormat( this DateTime dateTime )
    {
       return dateTime.ToString("dddd, MMMM d, yyyy a\\t h:mm") +
              dateTime.ToString("tt").ToLower();
    }
}

...

item.PostedOn.MyDateFormat();

EDIT: Other ideas on how to do this at How to format a DateTime like "Oct. 10, 2008 10:43am CST" in C#.

睡美人的小仙女 2024-07-19 05:16:28

上述方法的问题在于,使用格式字符串的主要原因是为了启用本地化,并且到目前为止给出的方法对于任何不希望包含最后的 am 或 pm 的国家或文化来说都是无效的。 因此,我所做的就是写出一个扩展方法,该方法可以理解附加格式序列“TT”,它表示小写的 am/pm。 下面的代码针对我的情况进行了调试,但可能还不完美:

    /// <summary>
    /// Converts the value of the current System.DateTime object to its equivalent string representation using the specified format.  The format has extensions over C#s ordinary format string
    /// </summary>
    /// <param name="dt">this DateTime object</param>
    /// <param name="formatex">A DateTime format string, with special new abilities, such as TT being a lowercase version of 'tt'</param>
    /// <returns>A string representation of value of the current System.DateTime object as specified by format.</returns>
    public static string ToStringEx(this DateTime dt, string formatex)
    {
        string ret;
        if (!String.IsNullOrEmpty(formatex))
        {
            ret = "";
            string[] formatParts = formatex.Split(new[] { "TT" }, StringSplitOptions.None);
            for (int i = 0; i < formatParts.Length; i++)
            {
                if (i > 0)
                {
                    //since 'TT' is being used as the seperator sequence, insert lowercase AM or PM as appropriate
                    ret += dt.ToString("tt").ToLower();
                }
                string formatPart = formatParts[i];
                if (!String.IsNullOrEmpty(formatPart))
                {
                    ret += dt.ToString(formatPart);
                }
            }
        }
        else
        {
            ret = dt.ToString(formatex);
        }
        return ret;
    }

The problem with the above approaches is that the main reason you use a format string is to enable localization, and the approaches given so far would break for any country or culture that does not wish to include a final am or pm. So what I've done is written out an extension method that understands an additional format sequence 'TT' which signifies a lowercase am/pm. The below code is debugged for my cases, but may not yet be perfect:

    /// <summary>
    /// Converts the value of the current System.DateTime object to its equivalent string representation using the specified format.  The format has extensions over C#s ordinary format string
    /// </summary>
    /// <param name="dt">this DateTime object</param>
    /// <param name="formatex">A DateTime format string, with special new abilities, such as TT being a lowercase version of 'tt'</param>
    /// <returns>A string representation of value of the current System.DateTime object as specified by format.</returns>
    public static string ToStringEx(this DateTime dt, string formatex)
    {
        string ret;
        if (!String.IsNullOrEmpty(formatex))
        {
            ret = "";
            string[] formatParts = formatex.Split(new[] { "TT" }, StringSplitOptions.None);
            for (int i = 0; i < formatParts.Length; i++)
            {
                if (i > 0)
                {
                    //since 'TT' is being used as the seperator sequence, insert lowercase AM or PM as appropriate
                    ret += dt.ToString("tt").ToLower();
                }
                string formatPart = formatParts[i];
                if (!String.IsNullOrEmpty(formatPart))
                {
                    ret += dt.ToString(formatPart);
                }
            }
        }
        else
        {
            ret = dt.ToString(formatex);
        }
        return ret;
    }
攒一口袋星星 2024-07-19 05:16:28

这应该是所有这些选项中性能最高的。 但太糟糕了,他们无法在 DateTime 格式中使用小写选项(tt 与 TT 相反?)。

    public static string AmPm(this DateTime dt, bool lower = true)
    {
        return dt.Hour < 12 
            ? (lower ? "am" : "AM")
            : (lower ? "pm" : "PM");
    }

This should be the most performant of all these options. But too bad they couldn't work in a lowercase option into the DateTime format (tt opposite TT?).

    public static string AmPm(this DateTime dt, bool lower = true)
    {
        return dt.Hour < 12 
            ? (lower ? "am" : "AM")
            : (lower ? "pm" : "PM");
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文