Sitecore 8 DateFields are now UTC
After upgrading from Sitecore 7 to Sitecore 8 we started to notice that some of the dates shown across our site (in the format "22 Feb 2016") were showing a date one day earlier than expected.
This date is pulled from a DateField
on the item in Sitecore, and stepping through in the debugger it became apparent that the dates were off by exactly 11 hours. Eleven hours is the difference between our current timezone and UTC... suspicious! After a little bit of reading and checking the documentation I confirmed that this is indeed the case.
We were previously using an extension method named GetDateTime
which we used to return a DateTime?
value from a DateField
on an Item
, so it was simply a matter of tweaking it slightly to take advantage of the DateUtil.ToServerTime
method Sitecore already provides:
public static DateTime? GetLocalDateTime(this Item item, string fieldName)
{
var field = item.Fields[fieldName];
if(field != null)
{
var field = (DateField)item.Fields[fieldName];
var value = field.DateTime;
if(value.Year > 0001)
return DateUtil.ToServerTime(value);
}
return null;
}
I think my favourite thing about this issue was that our testing team initially missed this - because most of the testing was done in the afternoon! If an article was created after 11am, even subtracting 11 hours meant that it would still show the "correct" day. Only pages created before 11am would show the date for the previous day.