date format yyyy-MM-ddTHH:mm:ssZ

后端 未结 9 2162
走了就别回头了
走了就别回头了 2020-11-28 04:49

I assume this should be pretty simple, but could not get it :(. In this format Z is time zone.
T is long time pattern
How could I get a date in this format excep

相关标签:
9条回答
  • 2020-11-28 04:57

    Single Line code for this.

    var temp   =  DateTime.UtcNow.ToString("yyyy-MM-ddTHH\\:mm\\:ssZ");
    
    0 讨论(0)
  • 2020-11-28 04:57

    One option could be converting DateTime to ToUniversalTime() before converting to string using "o" format. For example,

    var dt = DateTime.Now.ToUniversalTime();
    Console.WriteLine(dt.ToString("o"));
    

    It will output:

    2016-01-31T20:16:01.9092348Z
    
    0 讨论(0)
  • 2020-11-28 05:00

    Look here at "u" and "s" patterns. First is without 'T' separator, and the second one is without timezone suffix.

    0 讨论(0)
  • 2020-11-28 05:01

    Using UTC

    ISO 8601 (MSDN datetime formats)

    Console.WriteLine(DateTime.UtcNow.ToString("s") + "Z");
    

    2009-11-13T10:39:35Z

    The Z is there because

    If the time is in UTC, add a 'Z' directly after the time without a space. 'Z' is the zone designator for the zero UTC offset. "09:30 UTC" is therefore represented as "09:30Z" or "0930Z". "14:45:15 UTC" would be "14:45:15Z" or "144515Z".

    If you want to include an offset

    int hours = TimeZoneInfo.Local.BaseUtcOffset.Hours;
    string offset = string.Format("{0}{1}",((hours >0)? "+" :""),hours.ToString("00"));
    string isoformat = DateTime.Now.ToString("s") + offset;
    Console.WriteLine(isoformat);
    

    Two things to note: + or - is needed after the time but obviously + doesn't show on positive numbers. According to wikipedia the offset can be in +hh format or +hh:mm. I've kept to just hours.

    As far as I know, RFC1123 (HTTP date, the "u" formatter) isn't meant to give time zone offsets. All times are intended to be GMT/UTC.

    0 讨论(0)
  • 2020-11-28 05:05
    Console.WriteLine(DateTime.UtcNow.ToString("o"));  
    Console.WriteLine(DateTime.Now.ToString("o"));
    

    Outputs:

    2012-07-09T19:22:09.1440844Z  
    2012-07-09T12:22:09.1440844-07:00
    
    0 讨论(0)
  • 2020-11-28 05:08

    "o" format is different for DateTime vs DateTimeOffset :(

    DateTime.UtcNow.ToString("o") -> "2016-03-09T03:30:25.1263499Z"
    
    DateTimeOffset.UtcNow.ToString("o") -> "2016-03-09T03:30:46.7775027+00:00"
    

    My final answer is

    DateTimeOffset.UtcDateTime.ToString("o")   //for DateTimeOffset type
    DateTime.UtcNow.ToString("o")              //for DateTime type
    
    0 讨论(0)
提交回复
热议问题