6

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?

user1234
  • 3,000
  • 4
  • 50
  • 102

3 Answers3

4

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) );
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
2

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));
cameraguy258
  • 609
  • 2
  • 9
  • 21
2

You can use Intl.DateTimeFormat, it's ECMA compatible and has major support:

// sometimes even the US needs 24-hour time
options = {
 year: 'numeric', month: 'numeric', day: 'numeric',
 hour: 'numeric', minute: 'numeric', second: 'numeric',
 hour12: false,
 timeZone: 'America/Los_Angeles' 
};
console.log(new Intl.DateTimeFormat('en-US', options).format(date));
// → "12/19/2012, 19:00:00"

You just have to play around to get what you want.

Marco
  • 2,757
  • 1
  • 19
  • 24