-3

I am getting a date string in ISO format (for example, '2012-10-16T17:57:28.556094Z'), but while printing it in my html page I should print it in 'MMM dd, yyyy' format (for example, 'Oct 17, 2012').

What is the simplest way to achieve this without using any library?

Thanks.

Sattyaki
  • 346
  • 2
  • 8
  • 1
    There are many, many questions already on [formatting dates](https://stackoverflow.com/search?q=%5Bjavascript%5D+how+to+format+a+date), find an answer that suits, write some code and post again if you have issues. – RobG Mar 05 '21 at 05:30

3 Answers3

3

You can use toLocaleDateString().

The toLocaleDateString() method returns a string with a language sensitive representation of the date portion of this date.

const date = new Date(),
      dateString = date.toLocaleDateString('en-US', {year: 'numeric', month: 'short', day: 'numeric'});
console.log(dateString);
Hassan Imam
  • 20,493
  • 5
  • 36
  • 47
1

You can use the Intl.DateTimeFormat for this (in supporting browsers).

You create a formatter with the options you want, in your case, the year should be "numeric", the month "short" and the day "numeric".

You can construct a date object using your ISO8601 string and then pass it to the formatter.

const formatter = new Intl.DateTimeFormat("en", { year: "numeric", month: "short", day: "numeric" });
const date = new Date("2012-10-16T17:57:28.556094Z");
formatter.format(date);
// => 'Oct 17, 2012'

Alternatively, you could set up an array of month names and use the getMonth, getDay and getFullYear methods of Date, like so:

const months = ["Jan", "Feb", ... , "Dec"];
const date = new Date("2012-10-16T17:57:28.556094Z");
`${months[date.getMonth()]} ${date.getDay()}, ${date.getFullYear()}`;
// => 'Oct 17, 2012'
philnash
  • 64,214
  • 10
  • 52
  • 79
0

Use Date.parse() to convert the string to a Date object, then extract the relevant data into a format string if none of the canned formats match (toDateString(), toLocaleString() etc).

Allan Wind
  • 11,844
  • 4
  • 24
  • 32