Saturday, 17 August 2013

How to convert string offset to timespan in c#

How to convert string offset to timespan in c#

I'm trying to convert the convert time to the user's time zone, but I
don't have the windows time zone string such as "Pacific Standard Time".
All I have is a string offset such as "-07:00". Looks like I need to
create a timespan. Is the only way to parse this string manually?. Seems
like there should be a way to convert a time using a string offset, but
maybe I am missing something.
I have this but it requires the timezone. I'm trying to modify it to use
the offset instead, but you can see the timespan that is created for the
conversion and I need to get my offset to the timespan.
static void Main(string[] args)
{
var currentTimeInPacificTime =
ConvertUtcTimeToTimeZone(DateTime.UtcNow, "Pacific Standard Time");
//TimeSpan ts = new TimeSpan("-07:00");
Console.ReadKey();
}
static DateTimeOffset ConvertUtcTimeToTimeZone(DateTime dateTime, string
toTimeZoneDesc)
{
if (dateTime.Kind != DateTimeKind.Utc) throw new Exception("dateTime
needs to have Kind property set to Utc");
TimeSpan toUtcOffset =
TimeZoneInfo.FindSystemTimeZoneById(toTimeZoneDesc).GetUtcOffset(dateTime);
var convertedTime = DateTime.SpecifyKind(dateTime.Add(toUtcOffset),
DateTimeKind.Unspecified);
return new DateTimeOffset(convertedTime, toUtcOffset);
}

No comments:

Post a Comment