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

后端 未结 5 2106
一个人的身影
一个人的身影 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;
        }
    }
    
    0 讨论(0)
  • 2020-12-06 00:09

    TimeZoneInfo has a static method ConvertTimeToUtc which enables you to specify the datetime and timezone. This will to do the time adjustment for you, and return the UTC date.

    MSDN documentation is http://msdn.microsoft.com/en-us/library/bb495915.aspx, complete with example.

    0 讨论(0)
  • 2020-12-06 00:17

    This seems to work for me when I need to parse a datetime string from a known timezone into my local one. Haven't tested it in many cases but so far it has worked great for parsing times on a server somewhere in the eu.

    TimeZoneInfo.ConvertTime(DateTime.Parse("2012-05-25 23:17:15", CultureInfo.CreateSpecificCulture("en-EU")),TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time"),TimeZoneInfo.Local)
    
    0 讨论(0)
  • 2020-12-06 00:17

    Simplest solution: First parse string to local DateTime, use any parse method then call

    new DateTimeOffset(dateTimeLocal.Ticks, timezone.BaseUtcOffset)
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题