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
  • 28,160
  • 11
  • 74
  • 110

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
  • 230,703
  • 74
  • 448
  • 575
Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
  • Nice!!! but how can I make FindSystemTimeZoneById() dynamic. means it automatically select the timezoneinfo for system. – Zaheer Ahmed May 07 '13 at 07:56
  • @ZaheerAhmed Check my edit, I changed it to use the `CurrentTimeZone` property. – Mathew Thompson May 07 '13 at 08:00
  • 1
    I updated your code. The `StandardName` and the `Id` are not the same thing. (`Id` is invariant, `StandardName` is for display and can be localized). And there's no need to look it up - it's always there in `TimeZoneInfo.Local`. – Matt Johnson-Pint May 15 '13 at 16:31