Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change the timezone of datetimeoffset

I have a DateTimeOffset variable whose value is 11-11-1989 16:00:00 +03:30. I can call ToLocalTime() method on it and it shows 11-11-1989 18:00:00 +05:30. (I am in India :p)

I am looking for something like this: variable1.ToOffset(<timespan>)

If I give this function a timespan of 3 hours, It should return me 11-11-1989 19:00:00 +06:30.

I tried to change the offset, but offset property is read-only. Does anyone know any workaround for this ?

like image 250
Bilal Fazlani Avatar asked May 30 '13 10:05

Bilal Fazlani


2 Answers

This is stupid. But there is a function named ToOffset and it takes timespan as input parameter!

like image 135
Bilal Fazlani Avatar answered Oct 03 '22 15:10

Bilal Fazlani


For future readers: I've had a DateTimeOffset that was parsed without timezone. So to change the timezone only, without affecting the actual time you have to subtract the timespan again as in underlying code.

e.g. 2018-03-27T11:00:00 +00:00 => 2018-03-27T11:00:00 +02:00

static DateTimeOffset ChangeUtcToCest(DateTimeOffset original)
{
    TimeZoneInfo cetInfo = TimeZoneInfo.FindSystemTimeZoneById("Central Europe Standard Time");
    DateTimeOffset cetTime = TimeZoneInfo.ConvertTime(original, cetInfo);
    return original
        .Subtract(cetTime.Offset)
        .ToOffset(cetTime.Offset);
}
like image 45
Sam Segers Avatar answered Oct 03 '22 16:10

Sam Segers