4

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?

Community
  • 1
  • 1
Zaheer Ahmed
  • 27,470
  • 11
  • 72
  • 109

1 Answers1

1

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);
Matt Johnson-Pint
  • 214,338
  • 71
  • 421
  • 539
mattytommo
  • 54,375
  • 15
  • 123
  • 144