0

Let's say I have a string 2021-08-13 and want to convert this to August 13, 2021. How would you achieve this as it's not a date object.

In my mind I can think of setting each numeric month to a text version of that month and re-arrange, however seeing if there are better ways of doing this.

Eric Nguyen
  • 926
  • 3
  • 15
  • 37
  • By turning it into a Date object and then using `DateTimeFormat` [with options](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat#using_options). – Mike 'Pomax' Kamermans Aug 18 '21 at 17:00

2 Answers2

0

Simple: convert the string into a Date object and use the toLocaleString function.

If you want to get rid of the timezone so the date stays the same wherever the user is you can first convert it into an ISO string, get rid of the 'Z' in the end, and then convert it back into the Date object.

const dateString = '2021-08-13'
const localeOptions = {dateStyle: 'long'}

const dateTimezone = new Date(dateString).toLocaleString('en-US', localeOptions)
const dateWithoutTimezone = new Date(new Date(dateString).toISOString().slice(0,-1)).toLocaleString('en-US', localeOptions)

console.log(dateTimezone)
console.log(dateWithoutTimezone)
  • '2021-08-13' is parsed as UTC so will not produce the expected date in places west of Greenwich, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Aug 18 '21 at 20:35
  • Yes, and that's precisely why I mentioned how to remove the timezone. Didn't understand your point. – Rafael de Freitas Aug 18 '21 at 21:02
  • There is no explanation of why the first example fails, nor why "*If you want to get rid of the timezone…*" is necessary when there isn't one. The inefficiency of `string -> Date -> string -> string -> Date -> string` vs `string -> Date -> string` or `string -> string` should be clear. – RobG Aug 19 '21 at 04:00
-1

Convert your string date to a JS Date Object

let strDate = "2021-08-13";
let date = new Date(strDate);

console.log(date.toDateString())

Learn more about Date object here: JavaScript Date

ahsan
  • 1,409
  • 8
  • 11