Bilal Fazlani
Bilal Fazlani

Reputation: 6967

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 ?

Upvotes: 9

Views: 21673

Answers (2)

Sam Segers
Sam Segers

Reputation: 1951

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);
}

Upvotes: 13

Bilal Fazlani
Bilal Fazlani

Reputation: 6967

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

Upvotes: 20

Related Questions