.NET Tip of The Day
Learn one new .NET trick every day
Web GTD system from the creators of DotNetTipOfTheDay.org          Login or Join

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.

8/7/2007
RSS .NET Tip of The Day
Subscribe to receive one tip from the .NET Tips and Tricks Community per day.
Previous Tips of The Day
The best of the .NET Tips & Tricks Community.
.NET Practitioners .NET Tips & Tricks Community
Every .NET practitioner has a trick up in their sleeve. This is the place to share it with other .NET people.
Submit a Tip
Discovered a new trick? Share it with others.
My Tips
Manage tips you authored.