Parse a date string into a certain timezone (supporting daylight saving time)

后端 未结 5 2118
一个人的身影
一个人的身影 2020-12-05 23:48

Ok i\'ve been working very hard the last few weeks and i\'ve come across a small problem. I don\'t think my mind is quite up to the task right now :) so i need some tips/hel

5条回答
  •  -上瘾入骨i
    2020-12-06 00:20

    Heres a simple solution for a predefined format, this can be dynamic as well. I personally use this for talking with javascript:

    public DateTimeOffset ParseDateExactForTimeZone(string dateTime, TimeZoneInfo timezone)
    {
        var parsedDateLocal = DateTimeOffset.ParseExact(dateTime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
        var tzOffset = timezone.GetUtcOffset(parsedDateLocal.DateTime);
        var parsedDateTimeZone = new DateTimeOffset(parsedDateLocal.DateTime, tzOffset);
        return parsedDateTimeZone;
    }
    

提交回复
热议问题