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

后端 未结 5 2120
一个人的身影
一个人的身影 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条回答
  •  南方客
    南方客 (楼主)
    2020-12-06 00:08

    As no-one has provided any better solutions (which is very surprising!) i'm accept my own function as the answer, although i might make the function more concise and re-work it a bit later:

    public DateTimeOffset ReadStringWithTimeZone(string EnteredDate, TimeZoneInfo tzi)
    {
        DateTimeOffset cvUTCToTZI = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, tzi);
        DateTimeOffset cvParsedDate = DateTimeOffset.MinValue;
        DateTimeOffset.TryParse(EnteredDate + " " + cvUTCToTZI.ToString("zzz"), out cvParsedDate);
        if (tzi.SupportsDaylightSavingTime)
        {
            TimeSpan getDiff = tzi.GetUtcOffset(cvParsedDate);
            string MakeFinalOffset = (getDiff.Hours < 0 ? "-" : "+") + (getDiff.Hours > 9 ? "" : "0") + getDiff.Hours + ":" + (getDiff.Minutes > 9 ? "" : "0") + getDiff.Minutes;
            DateTimeOffset.TryParse(EnteredDate + " " + MakeFinalOffset, out cvParsedDate);
            return cvParsedDate;
        }
        else
        {
            return cvParsedDate;
        }
    }
    

提交回复
热议问题