How to deal with datetime values and CSOM

Every developer know that working with dates (or datetimes) is never straightforward. Sometimes it is a real pain. Yesterday I needed to solve a problem in an old project. An external website that is using SharePoint lists as datastore. The application uses the SharePoint client side object model to communicate with the SharePoint server. Everything works fine except when I wanted to visualize the date columns on a webpage. For some reason the dates were wrong. When I took a deeper look into it it seems that the dates were stored right in the SharePoint list but in the webapplication there were 2 hours “lost”. For example 2014-09-20 10:25:00 was shown as 2014-09-20 08:25:00. Aha… a timezone issue J

The following code fixed the problem:

Dim tz As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(“Central European Standard Time”)

Dim hours As Integer = tz.GetUtcOffset(obj.ArrivalDate).Hours

obj.ArrivalDate = CType(item(“Arrivaldate”), Date).AddHours(hours)

obj.DepartureDate = CType(item(“Departuredate”), Date).AddHours(hours)

 

To find out more about the TimeZoneInfo you can check the MSDN page.