Zaheer Ahmed
Zaheer Ahmed

Reputation: 28548

DayLight Saving Time issue of DateTime from JavaScriptSerializer.Serialize to ToLocalTime

Previously I was facing this issue and solved as described in the post.

Currently after DayLight Saving implementation I observed the issue that if I am selecting

 DateTime startDate=new DateTime(2012,1,20); //Eastern Timezone (UTC -5:00)

after serializing it would convert it to:

string serializeDate= serializer.Serialize(startDate); //In ticks 20-Jan 2012 05:00AM

on deserializing and ToLocalTime()

DateTime afterDeserialize= serializer.Deserialize<DateTime>(serializeDate);
afterDeserialize.ToLocalTime();

It was working perfect until:

datetime zone

I unchecked the Automatically adjust clock for Daylight Saving Time.

Now its on serialization add 4:00 hours (due to Daylight Saving Time) but on ToLocalTime() subtracting -5:00 hours due to environment daylight saving time which change the date of my object subtracting one day.

How I can inject the current environment Daylight Saving time on both conversion?

Upvotes: 4

Views: 2247

Answers (1)

Mathew Thompson
Mathew Thompson

Reputation: 56429

You'd need to store the offset for your timezone, then re-apply it after conversion.

To make it dynamic (as you said in comments), you can first get current timezone:

TimeZoneInfo tzi = TimeZoneInfo.Local;
TimeSpan offset = tzi.GetUtcOffset(myDateTime);

Then do:

DateTime startDate=new DateTime(2012,1,20).Add(offset);

Then after serialization:

DateTime afterDeserialize= serializer.Deserialize<DateTime>(serializeDate);
afterDeserialize.ToLocalTime().AddOffset(offset);

Upvotes: 1

Related Questions