Best Practices For Date Manipulation With Momentjs And Sharepoint

The Need for Date Manipulation

SharePoint stores dates and times in Coordinated Universal Time (UTC) format rather than local time zones. This facilitates internal operations, calculations, and storage. However, it can cause confusion when dates and times are displayed to users in different time zones. The time zone offset is not inherently accounted for when rendering dates stored in UTC.

Manual conversion of dates and times from UTC to local time zones is tedious and error-prone. The complexities of daylight saving time, leap years, and varied calendars across global regions make this a significant challenge. As a result, dates can appear incorrect to SharePoint users unless timezone offsets are properly applied.

MomentJS Overcomes Date Issues

MomentJS is an open-source JavaScript library designed specifically for parsing, manipulating, and formatting dates and times. It accounts for issues that complicate date handling such as time zones, daylight saving time transitions, leap years, and more. MomentJS provides intuitive functions for getting and setting date components like year, month, day, hour, minute, seconds, milliseconds etc.

As an open source library, MomentJS benefits from contributions from developers across the world. It has widespread adoption and is supported in all major browsers. Using MomentJS minimizes the complexity around handling dates in SharePoint implementations.

Basic Usage of MomentJS

Installing MomentJS

To use MomentJS in SharePoint, first add a script editor web part to the desired page. Then insert a script tag that references the MomentJS library hosted on a CDN as shown below:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

Creating Moment Objects from SharePoint Dates

Once added, MomentJS can be instantiated with the SharePoint UTC date string. This creates a Moment object mapped to that date. For example:

var spDateString = "2023-02-27T14:32:00Z";
var momentDate = moment(spDateString);

Formatting Moment Dates for Display

Dates stored in Moment objects can be formatted as desired using the .format() function. Some examples:

momentDate.format("MM/DD/YYYY"); // 02/27/2023
momentDate.format("hh:mm a"); // 09:32 am 
momentDate.format("dddd LL"); // Monday February 27

Getting and Setting Date Components

Date components like day, month, year etc can be get and set easily like:

var day = momentDate.date(); // 27  
momentDate.month(0); // sets January

Advanced Date Manipulation

Comparing Dates

Moment makes comparing two dates simple. For instance, checking if a date is after today:

var isFuture = moment("2025-01-01").isAfter(moment()); // true

Checking if Date In Daylight Savings

To test if a given date is within daylight savings time for its timezone:

momentDate.isDST(); // true or false

Adding and Subtracting Time Units

Add and subtract time units like days, weeks, years etc. from dates using add() and subtract() methods:

var nextWeek = moment().add(7, "days");  
var lastYear = moment().subtract(1, "years");

Determining Start and End of Date Ranges

Get the start and end dates for the current month:

var startMonth = moment().startOf("month").format("ll"); // "February 1, 2023"  
var endMonth = moment().endOf("month").format("ll"); // "February 28, 2023"

Displaying Formatted Dates

Date Localization with Multiple Languages

Localize date displays by chaining the .locale() function:

momentDate.locale("fr").format("LL"); // "27 février 2023"

Relative Times (e.g. “30 minutes ago”)

Display time relative to the current date and time:

var timeAgo = moment("2023-02-27T13:05:00").fromNow(); // "30 minutes ago"

Custom Display Formats

Build custom date and time display strings:

moment().format("[Today is] dddd, MMMM Do YYYY");  
// "Today is Monday, February 27th 2023"

Best Practices

  • Store dates in UTC internally for robustness
  • Format UTC dates to local time only when displaying to users
  • Use Moment locales for localized date displays
  • Watch out for daylight saving time boundaries when manipulating dates
  • Always create defensive copies of Moment objects before manipulation

Example Code Snippets

Common Operations

// Format to locale date string
var now = moment().format("L"); 

// Get and set date parts  
var day = moment().date(1);

// Add and subtract time
var nextYear = moment().add(1, "years");

// Compare dates
var isAnniversary = moment("2023-05-15").isSame(moment(), "day");

Localization

// French localization
moment().locale("fr").format("L");

// Localized calendar week output
moment().locale("en-gb").format("w ww wo"); 

Relative Time

// Relative time from now
moment("20200101", "YYYYMMDD").fromNow(); // "3 years ago"

// Relative time from date 
moment("20230130").to(moment("20230227")); // "27 days"

Conclusion

MomentJS makes manipulating and formatting of dates in SharePoint significantly easier compared to native JavaScript Date handling. By encapsulating complex logic behind an intuitive interface, common date and time operations are greatly simplified.

Following the best practices around defensive copies, UTC storage, and daylight savings boundaries will result in robust date handling code. The example snippets and extensive documentation enable rapid implementation in SharePoint solutions.

Leave a Reply

Your email address will not be published. Required fields are marked *