Skip to content

Instantly share code, notes, and snippets.

@kdarty
Created November 12, 2015 18:43
Show Gist options
  • Save kdarty/b9ec1662c3c0205f06bc to your computer and use it in GitHub Desktop.
Save kdarty/b9ec1662c3c0205f06bc to your computer and use it in GitHub Desktop.
A topic that comes up often is how to Convert a Date or DateTime to "JSON Date". While there really isn't such a thing as a "JSON Date" Format, what it really is is a UNIX Time Format. While there is a standardized "sortable" DateTime Format, this "JSON Date" Format works quite well when dealing with JavaScript.
// Convert DateTime to "JSON Date" Format
// Adapted From: http://overpie.com/javascript/articles/convert-datetime-to-JSON-datetime-format
function convertToJSONDate(strDate) {
var dt = new Date(strDate);
var newDate = new Date(Date.UTC(dt.getFullYear(), dt.getMonth(), dt.getDate(), dt.getHours(), dt.getMinutes(), dt.getSeconds(), dt.getMilliseconds()));
return newDate.getTime().toString();
}
/* Typical Example formatting Date from C# WebAPI Method (JSON) */
// Retrieve and Parse Start Date from JSON
startDate = new Date(parseInt(data[index].DateCreated.substr(6)));
// Convert Start Date to "JSON" Date Format
startDateJSON = convertToJSONDate(startDate);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment