DateTime.ParseExact AM / PM指示符小写

时间:2015-04-20 20:36:21

标签: c# datetime formatting

考虑以下字符串......

var myString = "11/05/2015 01:04:16 p.m."

我可以对此字符串执行DateTime.ParseExact而不强制字符串大写吗? am / pm指示器让我感到悲伤,并且因为它是小写的而无法解析。我有一个静态类,其中包含格式字符串的常量。是否有用于指定小写am / pm指示符的格式标记?

格式字符串

namespace myProgram
{
    public static class MyFormatStrings
    {
        public const string MyDateTimeFormat = "dd/MM/yyyy hh:mm:ss t\\.\\M\\.";
    }
}

解析逻辑

namespace myProgram
{
    public static class MyProgram
    {
        public void MyMethod()
        {
            var myStringDateValue = "11/05/2015 01:04:16 p.m.";
            var result = DateTime.ParseExact(myStringDateValue, MyFormatStrings.MyDateTimeFormat, CultureInfo.InvariantCulture);
        }
    }
}

1 个答案:

答案 0 :(得分:4)

您可以更改文化中DateFormatInfo的AMDesignator / PMDesignator。

此信息为ReadOnly,因此您必须创建自己的文化:

我还更改了MyDateTimeFormat格式,以便它可以正常工作:

    public class MyCultureInfo : CultureInfo
    {
        public MyCultureInfo():base(CultureInfo.InvariantCulture.Name)
        {
        }
        public override DateTimeFormatInfo DateTimeFormat
        {
            get
            {
                DateTimeFormatInfo myDateTimeFormatInfo = base.DateTimeFormat;
                myDateTimeFormatInfo.PMDesignator = "p.m.";
                myDateTimeFormatInfo.AMDesignator = "a.m.";
                return myDateTimeFormatInfo;
            }
            set
            {
                base.DateTimeFormat = value;
            }
        }
    }
    public static class MyFormat
    {
        public const string MyDateTimeFormat = "dd/MM/yyyy hh:mm:ss tt";
    }
    static int Main(string[] args)
    {
        var myStringDateValue = "11/05/2015 01:04:16 p.m.";
        var result = DateTime.ParseExact(myStringDateValue, MyFormat.MyDateTimeFormat, new MyCultureInfo());
    }