Getting current GMT time

前端 未结 6 2111
鱼传尺愫
鱼传尺愫 2020-12-28 11:46

Is there a method in C# that returns the UTC (GMT) time zone? Not based on the system\'s time.

Basically I want to get the correct UTC time even if my system time is

6条回答
  •  萌比男神i
    2020-12-28 12:46

    You can simply hardcode a base DateTime in and calculate the difference between your given DateTime with that base to determine the precise desired DateTime as below code:

        string format = "ffffd dd MMM yyyy HH:mm:ss";     
        string utcBaseStr = "Wed 18 Nov 2020 07:31:34";
        string newyorkBaseStr = "Wed 18 Nov 2020 02:31:34";     
        string nowNewyorkStr = "Wed 18 Nov 2020 03:06:47";
        
        DateTime newyorkBase = DateTime.ParseExact(newyorkBaseStr, format, CultureInfo.InvariantCulture);
        DateTime utcBase = DateTime.ParseExact(utcBaseStr, format, CultureInfo.InvariantCulture);
        DateTime now = DateTime.ParseExact(nowNewyorkStr, format, CultureInfo.InvariantCulture);
        
        var diffMiliseconds = (now - newyorkBase).TotalMilliseconds;
        DateTime nowUtc = utcBase.AddMilliseconds(diffMiliseconds);
        
        Console.WriteLine("Newyork Base = " + newyorkBase);     
        Console.WriteLine("UTC Base = " + utcBase);
        Console.WriteLine("Newyork Now = " + now);      
        Console.WriteLine("Newyork UTC = " + nowUtc);   
    

    The output of above code is as follow:

    Newyork Base = 11/18/2020 2:31:34 AM
    UTC Base = 11/18/2020 7:31:34 AM
    Newyork Now = 11/18/2020 3:06:47 AM
    Newyork UTC = 11/18/2020 8:06:47 AM
    

提交回复
热议问题