Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

timespan and UTC

Tags:

.net

I have a Timespan variable, which has time in local time zone but for a database ( cold type time) I need to pass UTC . How do I do this? Also I need to get UTC to Local time to populate Timespan variable on pageLoad. Thanks!!!

like image 755
user228777 Avatar asked Jul 28 '10 14:07

user228777


1 Answers

A problem I found with a couple of the previous answers is that creating a DateTime from ticks results in a date/time such as 0001-01-01 04:00:00. If you're in a timezone with a positive UTC offset when the framework attempts to subtract say 10 hours it goes below DateTime.MinValue and while it doesn't throw an exception you end up with a TimeSpan containing 00:00:00 instead of the correct result.

The answer by Ali Sepehri.Kh gets around this underflow by using .AddDays(1) however because the date is always January 1 for areas that observe DST you can end up with an incorrect result. Because I was only interested in timespans for the current day I ended up using a modified version of Ali's code that uses the current date as the base and adds the TimeSpan to it:

public static TimeSpan LocalTimeSpanToUTC(TimeSpan ts)
{
    DateTime dt = DateTime.Now.Date.Add(ts);
    DateTime dtUtc = dt.ToUniversalTime();
    TimeSpan tsUtc = dtUtc.TimeOfDay;
    return tsUtc;
}

public static TimeSpan UTCTimeSpanToLocal(TimeSpan tsUtc)
{
     DateTime dtUtc = DateTime.UtcNow.Date.Add(tsUtc);
     DateTime dt = dtUtc.ToLocalTime();
     TimeSpan ts = dt.TimeOfDay;
     return ts;
}
like image 194
PeterJ Avatar answered Oct 10 '22 03:10

PeterJ