I'm too late to the party since this question is already a decade old, but I want to provide a cleaner one without the use of any plugins like moment.js
. only vanilla javascript.
export default {
// Accepts "1998-08-06 11:00:00" <-- This is UTC timestamp
getFormalDateTime(utcDate) {
const formattedUtc = utcDate.split(' ').join('T')+'Z'
let date = new Date(formattedUtc);
if (date.toString() === "Invalid Date")
return "N/A";
let dateString = date.toLocaleDateString("en-US", {month: 'long', day: 'numeric', year: 'numeric'});
let timeString = date.toLocaleTimeString("en-US", {hour: 'numeric', minute: 'numeric', hour12: true});
let formattedDate = dateString + " | " + timeString;
return formattedDate; // Returns "August 6, 1998 | 11:00 AM" <-- This is converted to client time zone.
},
// Accepts: "1998-08-06"
getFormalDate(convertDate) {
let date = new Date(convertDate);
if (date.toString() === "Invalid Date")
return "N/A";
let dateString = date.toLocaleDateString("en-US", {month: 'long', day: 'numeric', year: 'numeric'});
return dateString // Returns "August 6, 1998"
}
}
My code is formatted for ES6 modules
because I use it as a module for my vuejs project but you can convert it to a normal javascript function.
getFormalDateTime('1998-08-06 11:00:00')
the parameter should be in UTC
time. This will return a formal date time converted to the client/browser timezone: August 6, 1998 | 11:00 AM
getFormalDate('1998-08-06')
will just return August 6, 1998
More information here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString