javascript date format - vanilla
function formatDate( date, params ) {
var options = {
weekday: "short",
year: "numeric",
month: "long",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
timeZone: "UTC",
timeZoneName: "short",
};
if( params ) {
options = Object.assign( options, params );
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
return new Date( date ).toLocaleString( 'en-US', options );
}
formatDate( 'Invalid Date String' ); // bad date
formatDate( new Date() );
formatDate( +new Date() ); // timestamp
formatDate( '2016-08-11' ); // Thu, August 11, 2016, 12:00 AM GMT
formatDate( '08/11/2016' );
// 8/11/2016, 7:00 AM
formatDate( '08/11/2016', {
weekday: undefined,
month: "numeric",
timeZoneName: undefined
} );Written by Bruce Lim
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Date
Authors
goker
24.61K
raviolicode
16.36K
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#