How to format SharePoint Date to DD-MM-YYYY Format using Moment.js

It’s easy to format SharePoint Date in JavaScript Date Format e.g. mm/dd/yyyy OR dd/mm/yyyy

Use below code to format Date

Add Moment.js Reference

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

Apply Date Format as per shown code


    //Get SharePoint Date Column Value 
    var itemBirthDate = items[i].BirthDate;   
    //Convert SharePoint Date to Javascript Date 
    var dateObj = new Date(itemBirthDate);
    //Convet JavaScript Date Object to Moment JS
    var momentObj = moment(dateObj);
    //Apply Moment.Js Formatter to your desire date format
    var formattedDate = momentObj.format('DD-MM-YYYY');   
    $("#divContent").append("Username : " + itemTitle + "  BirthDate :  " + formattedDate +" <br/>  ");      

Sample Code to retrieve item and Date Format

function GetData() {

	var listName = "Controls";
	var siteurl = _spPageContextInfo.webAbsoluteUrl;
	var condition = "$select=Title,BirthDate";

	getListItems(listName, siteurl, condition, function (data) {

		var items = data.d.results;

		for (var i = 0; i < items.length; i++) {
			var itemTitle = items[i].Title;
			//Get SharePoint Date Column Value 
			var itemBirthDate = items[i].BirthDate;
			//Convert SharePoint Date to Javascript Date 
			var dateObj = new Date(itemBirthDate);
			//Convet JavaScript Date Object to Moment JS
			var momentObj = moment(dateObj);
			//Apply Moment.Js Formatter to your desire date format
			var formattedDate = momentObj.format('DD-MM-YYYY');
			$("#divContent").append("Username : " + itemTitle + "  BirthDate :  " + formattedDate + " <br/>  ");
		}
	}, function (data) {
		alert("Ooops, an error occured. Please try again");
	});
}

function getListItems(listName, siteurl, condition, success, failure) {
	$.ajax({
		url: siteurl + "/_api/web/lists/getbytitle('" + listName + "')/items?" + condition,
		method: "GET",
		async: false,
		headers: {
			"Accept": "application/json; odata=verbose"
		},
		success: function (data) {
			success(data);
		},
		error: function (data) {
			failure(data);
		}
	});
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s