Javascript Date Time Formatting
Overview Creating Date Objects Examples
Documentation
In Javascript, you can represent a single moment in time by instantiating a Date object. Javascript will use the browsers date and time by default when choosing what moment in time to use. Although many people choose to use Javascript to format dates, there are plenty of Javascript Libraries that provide a more robust and extensive toolset for formatting date and time. Further documentation on the Date object in javascript can be found below:
https://www.w3schools.com/js/js_dates.asp
Creating Date Objects
There are 4 different ways that you can instantiate a new Date using the javascript Date Constructor:
new Date()
new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date(milliseconds)
new Date(date string)
Examples
Below you can find an example function that takes in a date object, and then prints it formatted like: 11/26/2018 10:22 am
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var timeTxt = hours + ':' + minutes + ' ' + ampm;
return date.getMonth()+1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + timeTxt;
}
var d = new Date();
var today = formatDate(d);
alert(today);