Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert the timestamp into ("MMM DD, HH:mm") format. JS [duplicate]

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?

like image 322
user1234 Avatar asked Apr 22 '19 23:04

user1234


People also ask

What date format is DD MMM YYYY JavaScript?

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.

What is the format of new date ()?

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).

How to get current date using moment js?

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.


2 Answers

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));
like image 30
cameraguy258 Avatar answered Oct 28 '22 16:10

cameraguy258


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) );
like image 89
Mister Jojo Avatar answered Oct 28 '22 16:10

Mister Jojo