SharePoint Search: Localization of Date and Time field
Overview
It's a very common scenario to get results from SharePoint search and show it using our custom display templates.
One of the notorious fields is DateTime. SharePoint internally stores all DateTime field in UTC format. But, while displayed over a SharePoint form, it converts to Site's Time Zone in Regional Setting OR Browser's Local (i.e. User's local Date Time).
JavaScript Localization
SharePoint Search returns DateTime fields in stored TimeZone i.e. UTC. So, in case of custom display templates, we need to take care of Time Zone conversion to Local. It can be tricky to manipulate Date Time; wouldn't it be easier if JavaScript running in browser take care of it by self?
The trick is adding the missing string "UTC" in search result field.
When a search returns DateTime field it does not append "UTC" in the end, so the browser does not know which Time Zone it is and treat it as local Time Zone. That's why we get different times shown in Search than in an actual event.
The fix is to append "UTC" at the end of our DateTime field,
var startTime = $getItemValue(ctx, "RefinableDate18"); var localStart = new Date(startTime.value.toString() + " UTC");
var endTime = $getItemValue(ctx, "RefinableDate19"); var localEnd = new Date(endTime.value.toString() + " UTC");
By appending 'UTC' in the end, we are letting JavaScript know the correct TimeZone of the field and it will internally convert it to Local.
Similar fix in JS
var RefinableDate18 = "6/22/2017 5:00:00 PM";
//Wrong local time as it has taken UTC as local TimeZone.
var serverDate = new Date(RefinableDate18); //Thu Jun 22 2017 17:00:00 GMT-0400 (Eastern Daylight Time)
//Correct local time
var localDate = new Date(RefinableDate18 + " UTC"); //Thu Jun 22 2017 13:00:00 GMT-0400 (Eastern Daylight Time)
Using above modification we can show DateTime field in the correct local TimeZone.