I have a date returned as a timestamp from the the server response and I want to convert it to ("MMM DD, HH:mm")
format using the toUTCString()
. so far I have this:
date = new Date(1555649122787).toUTCString()
o/p:
"Mon, 22 Apr 2019 23:00:32 GMT"
, however I want the o/p in this format:
Apr 22, 23:00
. Unfortunately for my project I'm unable to use moment.js as a library. any other better ways?
There is no native format in JavaScript for” dd-mmm-yyyy”. To get the date format “dd-mmm-yyyy”, we are going to use regular expression in JavaScript.
By default, when you run new Date() in your terminal, it uses your browser's time zone and displays the date as a full text string, like Fri Jul 02 2021 12:44:45 GMT+0100 (British Summer Time).
To get the current date and time, just call javascript moment() with no parameters like so: var now = moment(); This is essentially the same as calling moment(new Date()) . Unless you specify a time zone offset, parsing a string will create a date in the current time zone.
Try this:
function formatDate(date) {
let months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return `${months[date.getMonth()]} ${date.getDate()}, ${date.getHours()}:${date.getMinutes()}`;
}
date = new Date(1555649122787)
console.log(formatDate(date));
as Marco answering Intl.DateTimeFormat is the best way, but he forgot to mention that we can remove the elements of dates that we do not want
dateC = new Date(1555649122787);
B_Options = {
month: 'short', day: 'numeric',
hour: '2-digit', minute: '2-digit',
hour12: false,
timeZone: 'America/Los_Angeles'
};
console.log(new Intl.DateTimeFormat('en-US', B_Options).format(dateC) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With