How to get UTC equivalent for my local time in C#

前端 未结 3 620
情话喂你
情话喂你 2021-02-08 03:08

My machine is on PDT and if I say DateTime.Now, then I will get a local time which is say equivalent to Sep-18th 2012 6:00:00 AM. I want to get UTC equivalent for this datetime

相关标签:
3条回答
  • 2021-02-08 03:51

    Use DateTime.ToUniversalTime Method.

    0 讨论(0)
  • 2021-02-08 03:52

    You can use

    var now = DateTime.UtcNow;
    

    To convert an existing DateTime, assuming it has time zone information, you can use DateTime.ToUniversalTime(). If you get the DateTime instance using e.g.

    var localNow = DateTime.Now;  // Has timezone info
    

    it will have time zone information. If you create it e.g. using a tick count, it will not contain timezone information unless you explicitly supply it.

    var unspecifiedNow = new DateTime(someTickCount); // No timezone info
    

    It is worth mentioning that timezone handling in .NET is not optimal.  You may wish to have a look at Noda Time (a project by Jon Skeet) if you need to do anything elaborate involving time zones.

    0 讨论(0)
  • 2021-02-08 04:07

    If you want to convert any date from your time-zone to UTC do this:

    TimeZone.CurrentTimeZone.ToUniversalTime(myLocalDateTime)
    

    If you want to convert it back from UTC:

    TimeZone.CurrentTimeZone.ToLocalTime(myUtcDateTime)
    
    0 讨论(0)
提交回复
热议问题