The Situation

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 time zones. We recently encountered a rather interesting issue when applying date-based searching in SharePoint and time zones.

As part of an information portal we 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. No reference to the timezone difference. This means that for Melbourne (UTC+10), selecting 15/12/2017 will result in 2017-12-14T14:00:00. It removes 10 hours from the date for storage. When initialising a date object in JavaScript, it will adjust for timezone and leave us with 2017-12-15T00:00:00. No issues yet.

The Problem

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. If we were searching for a date range of 15/12/2017 to 22/12/2017, the article wouldn’t come up!

The Solution

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!