格式化ISO datetime为March 12, 2014 12:00:00

本文关键字:2014 March ISO datetime 格式化 | 更新日期: 2023-09-27 17:50:58

如何将ISO日期(20140312120000或2014-03-12 12:00:00)转换为"March 12, 2014 12:00:00" .

谢谢。

格式化ISO datetime为March 12, 2014 12:00:00

 DateTime thisDate1 = new DateTime(2014, 3, 12);
Console.WriteLine("Today is " + thisDate1.ToString("MMMM dd, yyyy") + ".");
// The example displays the following output: 
//    Today is March 12, 2011. 

你不能用普通的DateTime来解析它。解析方法,

DateTime.ParseExact(date, "yyyyMMdd''HHmmss", CultureInfo.InvariantCulture)

我是这样解决的:DateTime.Parse(isodate)。ToString("MMMM dd, yyyy HH:mm:ss").

您要做的是将输入字符串解析为DateTime,然后将其转换为您想要的形式。ParseExactToString方法可以完成这项工作。

public string MyFromat(string s)
{
    var inputForms = new string[] 
    { 
       "yyyyMMdd''HHmmss", 
       "yyyy-MM-dd' 'HH':'mm':'ss"
    };
    var time = DateTime.ParseExact(s, inputForms, , CultureInfo.InvariantCulture);
    return time.ToString(""MMMM dd, yyyy HH':'mm':'dd", , CultureInfo.InvariantCulture);
}

您的两个示例形式不是ISO。如果要解析ISO日期时间,则使用DateTimeOffset表示时间,并使用以下输入格式:

        static readonly string[] Iso8061DateTimeForms = new string[]
        {
               "yyyyMMdd'T'HHmmss",
               "yyyyMMdd'T'HHmmss'Z'",
               "yyyyMMdd'T'HHmmsszzz",
               "yyyyMMdd'T'HHmmss'.'fffffff",
               "yyyyMMdd'T'HHmmss'.'fffffff'Z'",
               "yyyyMMdd'T'HHmmss'.'fffffffzzz",
               "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
               "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'",
               "yyyy'-'MM'-'dd'T'HH':'mm':'sszzz",
               "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffff",
               "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffff'Z'",
               "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz",
        };
解析ISO 8061时间的完整实现是:
 public static DateTimeOffset ParseIso8061Time(string s)
 {
    var styles = DateTimeStyles.AllowWhiteSpaces |
        (s.EndsWith("Z") 
           ? DateTimeStyles.AssumeUniversal 
           : DateTimeStyles.AssumeLocal);
    return DateTimeOffset.ParseExact(s, Iso8061DateTimeForms,
        CultureInfo.InvariantCulture, styles);
 }