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
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;
}
}
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.
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)
Simplest solution: First parse string to local DateTime, use any parse method then call
new DateTimeOffset(dateTimeLocal.Ticks, timezone.BaseUtcOffset)
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;
}