Having problems with converting my DateTime to UTC

前端 未结 5 788
抹茶落季
抹茶落季 2020-12-23 13:25

I am storing all my dates in UTC format in my database. I ask the user for their timezone and I want to use their time zone plus what I am guessing is the server time to fig

5条回答
  •  失恋的感觉
    2020-12-23 13:56

    Everyone else's answer seems overly complex. I had a specific requirement and this worked fine for me:

    void Main()
    {
        var startDate = DateTime.Today;
        var StartDateUtc = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.SpecifyKind(startDate.Date, DateTimeKind.Unspecified), "Eastern Standard Time", "UTC");
        startDate.Dump();
        StartDateUtc.Dump();
    }
    

    Which outputs (from linqpad) what I expected:

    12/20/2013 12:00:00 AM

    12/20/2013 5:00:00 AM

    Props to Slaks for the Unspecified kind tip. That's what I was missing. But all the talk about there being only two kinds of dates (local and UTC) just muddled the issue for me.

    FYI -- the machine I ran this on was in Central Time Zone and DST was not in effect.

提交回复
热议问题