Kieran’s Tech Talk – Date-based searching in SharePoint and time zones

FiveP News

Kieran’s Tech Talk – Date-based searching in SharePoint and time zones

Kieran Cumming September 7, 2017
Kieran’s Tech Talk – Date-based searching in SharePoint and time zones

Anybody who has done any development in JavaScript knows that anything involving dates can be enormously painful to work with, especially in an application where users span multiple timezones. I recently encountered a rather interesting issue when applying date filters to retrieve article pages in SharePoint.

As part of an information portal I worked on recently, users needed the ability to enter a start and end date and retrieve a list of news articles with article dates within that range. Seems simple, right? It was… almost.

SharePoint search will store its dates in UTC format, with no reference to the timezone difference when it was created. This means that for Melbourne (UTC+10), selecting 15/12/2017 will result in 2017-12-14T14:00:00, as it removes 10 hours from the date for storage. When I initialise a date object in JavaScript, it will adjust for my timezone and leave me with 2017-12-15T00:00:00. No issues yet.

The problems we see however are when users from a timezone other than the one where the content was created try to query for data. For instance, if a user from Adelaide (UTC+9:30) searched for the article above, they would end up with 2017-12-14T23:30:00, so if I was searching for a date range of 15/12/2017 to 22/12/2017, the article wouldn’t come up!

Thankfully, I’m not the only person to have experienced this kind of issue. The fantastic moment.js library makes it far easier to work with dates in JavaScript, and Moment Timezone extension is built to handle situations such as these.

In SharePoint’s _spPageContextInfo object, the ‘webTimeZoneData’ property has an Id object to let us know which timezone is being used for the current site. Using this, and cross-referencing this list of SharePoint timezone ID to IANA time zone names, we could retrieve the right name to pass to Moment Timezone.

From there, we just ensured that any time we were using a data in JavaScript that we wrapped it in a moment object, and all of our timezone issues disappeared!

About the author: Kieran’s IT knowledge surpasses that of many elders. He does anything from back-end code to the user interface, he can script or code his way out of any problem.