0

How should I convert a date format of YYYY-MM-DD into a human readable format %e %B %Y in JS by taking into an account a different language from system's locale?

In PHP it would be like

<?php echo trim(strftime('%e %B %Y', strtotime('2019-07-31'))); ?>
// Renders: 31 July 2019

I want to have the same, but with a corresponding language locale, for example "French format" so it will become : 31 Juillet 2019

==== UPDATED ====

As mention by @Baljinder Singh, solution below from the link, works perfectly

console.log(
  new Date('2019-07-31').toLocaleDateString('fr-FR', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
)
aspirinemaga
  • 3,753
  • 10
  • 52
  • 95

2 Answers2

2

If it's browser-specific then you can make it dynamic with window.navigator.language.

const date = new Date('2019-07-31').toLocaleDateString(window.navigator.language, {
  year: 'numeric',
  month: 'long',
  day: 'numeric',
});

console.log(date);

Notice: Working fine in chrome and firefox.

Neel Rathod
  • 2,013
  • 12
  • 28
  • *window.navigator.language* is unreliable. – RobG Aug 20 '19 at 20:38
  • @RobG why It's unreliable – Neel Rathod Aug 21 '19 at 07:54
  • If you are dealing with **NodeJS** then you can use `req.headers["accept-language"] ` – Neel Rathod Aug 21 '19 at 08:03
  • It's unreliable because there is no requirement for it to be accurate, so it isn't. Many users are unaware of how to set or alter it. Some browsers do not read it from system settings, and even if they could, it may present a privacy or identity issue so they may not. The best solution is to ask the user, then use an unambiguous form, e.g. always use the month name or abbreviation rather than a number. PS online privacy is becoming a big issue, expect people to want to be as anonymous as possible. If a visitor is using a DE VPN but their browser language is en-NZ, what does that tell you? ;-) – RobG Aug 21 '19 at 09:19
  • Docs say: `To use the browser's default locale, pass an empty array.` – phil294 May 15 '22 at 20:45
1

Try

let d = new Date('2019-08-20');

let s = d.toLocaleDateString(navigator.languages,{day:"numeric", month:"long", year: "numeric"});

console.log(s);
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345