Search code examples
javascriptecmascript-6ecmascript-5

javascript: What is the shortest way to convert Unix to long date format


I have an ISO time string:

"2018-05-14T14:04:53.16"

I need to convert it to the following:

"May 05, 2018"

The way I know is to convert it first to a time stamp using parse, and then new Date:

let timestamp = new Date(Date.parse("2018-05-14T14:04:53.16"))

Then get each part seperatly, map them to map arrays, and then concating them:

let monthNames = ['January','Fabruary'...];
let month = timestamp.getMonth(); //gatDay/getYear
let monthName = monthNames[month - 1] 

then finaly concating all parts into a string:

let finalString = monthName+' '+day+', '+year;

Is there a shorter way to do this? Im asking because both of these date formats are recognized by javascript Date object, yet I cant find a short way to convert between the two.


Solution

  • You can convert timestamp to the desired format with toString and some string manipulation:

    timestamp.toString().replace(/\w+ (\w+ \d+)( \d+).*/, "$1,$2")