When developing custom solutions on the SharePoint platform we don’t really think about using DateTime objects anymore. We just build solutions using server-side DateTime.Now or DateTime.Today to check Date and Time and to check that with the values we get back from SharePoint. Because we have full control over our On-Premise environment we can be sure that the Server Date and Time is correct. However moving this principal to the Cloud we loose that bit of control. We have to make sure again we get the right Date and Time from the server to do accurate checks.
Timezone of a Office 365 Server
As soon as I was testing a solution using a DateTime.Now object to get Calendar Items I came across some strange behavior when testing before 09:00 (GMT +1). I came across this article http://onlinehelp.microsoft.com/en-us/office365-enterprises/hh531509.aspx to get all Applications in the right TimeZone. It seemed that the Office 365 servers were all set to the TimeZone GMT -8 (Which is the Redmond TimeZone). So there was a 9 hour difference (I’m in Amsterdam TimeZone GMT +1).
Because programming it like DateTime.Now.AddHours(9); didn’t seem the right thing to do, I found a good solution to get the right DateTime.Now based on our local TimeZone. First step is to set the Regional Settings for your Office 365 SharePoint Site Collection (https://MySharePointSite/_layouts/regionalsetng.aspx) to the correct TimeZone. With this Regional Settings we can use the SPRegionalSettings object to calculated the local time at the moment of need using the following code.
SPRegionalSettings reg = SPContext.Current.Site.RootWeb.RegionalSettings; SPTimeZone tz = reg.TimeZone; DateTime utc = DateTime.Now.ToUniversalTime(); DateTime utcLocal = tz.UTCToLocalTime(utc);
The utc represents DateTime.Now at GMT. With the UTCToLocalTime() method we will get the current DateTime based on our TimeZone. Now we can use utcLocal instead of DateTime.Now to get the accurate Date and Time when doing Server Side (Sandboxed) calculation with DateTime. The picture illustrates the DateTime.Now, the TimeZone ID set for the Current Site, GMT time and our LocalTime.