Tuesday, November 20, 2007

How to perform DateTime calculations in a right way

When coding, be careful if you need to perform DateTime calculations (add/subtract) on values representing time zones that practice daylight savings time. Unexpected calculation errors can result. Instead, convert the local time value to universal time, perform the calculation, and convert back to achieve maximum accuracy.

DateTime d;

d = DateTime.Parse("Oct 26, 2003 12:00:00 AM"); //date assignment

d = d.ToUniversalTime().AddHours(3.0).ToLocalTime();

//' - displays 10/26/2003 02:00:00 AM – Correct!

MessageBox.Show(d.ToString());

Working with DateTime structs seems to be simple, but it's not. Make sure you are aware of pitfalls discribed in the article Coding Best Practices Using DateTime in the .NET Framework.

No comments:

Post a Comment