timespan and UTC
class TimeConversion
{
public static TimeSpan LocalTimeSpanToUTC(TimeSpan ts)
{
DateTime dt = new DateTime(ts.Ticks).AddDays(1);
DateTime dtUtc = dt.ToUniversalTime();
TimeSpan tsUtc = dtUtc.TimeOfDay;
return tsUtc;
}
public static TimeSpan UTCTimeSpanToLocal(TimeSpan tsUtc)
{
DateTime dtUtc = new DateTime(tsUtc.Ticks).AddDays(1);
DateTime dt = dtUtc.ToLocalTime();
TimeSpan ts = dt.TimeOfDay;
return ts;
}
}
I suppose I would load the TimeSpan into a DateTime, then get the universal time from the DateTime and convert it back again.
var dt = new DateTime( timeSpan.Ticks );
var utc = dt.ToUniversalTime();
TimeSpan LocalTimeToUTCTime(TimeSpan localTime)
{
var dt = new DateTime(localTime.Ticks);
var utc = dt.ToUniversalTime();
return new TimeSpan(utc.Ticks);
}
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;
}