0

I have a date like 2019-02-01. how can I change it to February 2019?

Michael M.
  • 10,486
  • 9
  • 18
  • 34

3 Answers3

2

You can just do this:

const monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

const d = new Date("2019/02/01");
const dateString = `${monthNames[d.getMonth()]} ${d.getFullYear()}`;
console.log(dateString);

This will return the month in English, no matter the system's language.

Note that you should use new Date("2019/02/01") (with slashes) to specify a date in your timezone. If you use new Date("2019-02-01"), then it will assume UTC time, and weird stuff will happen (see this answer for more info on this).

Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • 1
    Any source where it says slashes = UTC? – vanowm Sep 27 '22 at 23:17
  • @vanowm It has to do with whether or not JS uses ISO-8601. Here's a SO answer that sums it up: https://stackoverflow.com/a/30199268/13376511 – Michael M. Sep 27 '22 at 23:20
  • @vanowm Oh sorry, I had a typo in my answer. I've updated it to correct it though. – Michael M. Sep 27 '22 at 23:22
  • 1
    MDN only states: Date-only strings (e.g. "1970-01-01") are treated as UTC, while date-time strings (e.g. "1970-01-01T12:00") are treated as local. It is good to know. Thanks. – vanowm Sep 27 '22 at 23:23
1

const d = new Date("2019/02/01");
const m = d.toLocaleString('default', { month: 'long' });
console.log(m, d.getFullYear());
Kyle
  • 1,463
  • 1
  • 12
  • 18
  • 1
    `Date.toLocaleString()` will return a month name in the user's language, not necessarily English. If OP needs February, then you need to change `'default'` to `'en-US'`. – Michael M. Sep 27 '22 at 22:53
0

/* you can use the following code to convert date to the required format. */ var todaysDate = new Date(); var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var formatted_date = months[todaysDate.getMonth()] + " " + todaysDate.getDate() + " " + todaysDate.getFullYear();

Doppani
  • 1
  • 1