Javascript: How to format the date according to the french convention

Viewed 10918

I use the toLocaleDateString method for formatting the date. This is how I do:

> var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
> var today  = new Date();
> today.toLocaleDateString("fr-FR", options);
"mercredi 23 octobre 2019" //The output

In French the usual format of the date is rather like this:

Mercredi, 23 octobre 2019

The first letter of the day of the week in capital letters and a comma just after. How can I adapt the code to this format?

3 Answers

Use moment.js:

moment().format('dddd, D MMMM YYYY');

See the formatting docs for more options

toLocaleDateString has very limited options for its output.

The toLocaleDateString() method returns a string with a language sensitive representation of the date portion of this date. The new locales and options arguments let applications specify the language whose formatting conventions should be used and allow to customize the behavior of the function.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

You'll want to define your own date string. Take a look at this question for a bunch of options.

How to format a JavaScript date

Thank you for your answers. Moment.js is a great library. Before migrating to Moment.js, I wrote a small code to work around the limitation of toLocaleDateString in order to get the format I want:

var options = {year: 'numeric', month: 'long', day: 'numeric' };
var opt_weekday = { weekday: 'long' };
var today  = new Date();
var weekday = toTitleCase(today.toLocaleDateString("fr-FR", opt_weekday));

function toTitleCase(str) {
    return str.replace(
        /\w\S*/g,
        function(txt) {
            return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
        }
    );
}

var the_date = weekday + ", " + today.toLocaleDateString("fr-FR", options)
// the output: "Jeudi, 24 octobre 2019"
Related