How can I format DateTime to web UTC format?

前端 未结 8 1928
梦毁少年i
梦毁少年i 2020-11-29 22:45

I have a DateTime which I want to format to \"2009-09-01T00:00:00.000Z\", but the following code gives me \"2009-09-01T00:00:00.000+01:00\" (both l

8条回答
  •  眼角桃花
    2020-11-29 23:09

    Some people have pointed out that ‘ToUniversalTime’ is somewhat unsafe in that it can cause unintended incorrect time dispalys. Expanding on that I’m providing a more detailed example of a solution. The sample here creates an extension to the DateTime object that safely returns a UTC DateTime where you can use ToString as desired….

    class Program
    {
        static void Main(string[] args)
        {
            DateTime dUtc = new DateTime(2016, 6, 1, 3, 17, 0, 0, DateTimeKind.Utc);
            DateTime dUnspecified = new DateTime(2016, 6, 1, 3, 17, 0, 0, DateTimeKind.Unspecified);
    
            //Sample of an unintended mangle:
            //Prints "2016-06-01 10:17:00Z"
            Console.WriteLine(dUnspecified.ToUniversalTime().ToString("u"));
    
            //Prints "2016 - 06 - 01 03:17:00Z"
            Console.WriteLine(dUtc.SafeUniversal().ToString("u"));
    
            //Prints "2016 - 06 - 01 03:17:00Z"
            Console.WriteLine(dUnspecified.SafeUniversal().ToString("u"));
        }
    }
    
    public static class ConvertExtensions
    {
        public static DateTime SafeUniversal(this DateTime inTime)
        {
            return (DateTimeKind.Unspecified == inTime.Kind)
                ? new DateTime(inTime.Ticks, DateTimeKind.Utc)
                : inTime.ToUniversalTime();
        }
    }
    

提交回复
热议问题