Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moment.js: how to get short date format?

My application sends an HTML file with javascript like this:

$(function () {
    moment.locale('fr');
    $('#datetimepicker9').datetimepicker({
        viewMode: 'years',
        locale: 'fr',
        format: '' /* <========= problem! */
    });
});

With moment, when I set to a locale, is there a way to get the short date format of the configuration like "'j F Y'" for fr?

I found it but it's hack-ish:

moment()['_locale']['_longDateFormat']['L']

So my code now:

$(function () {
    moment.locale('fr');
    $('#datetimepicker9').datetimepicker({
        viewMode: 'years',
        locale: 'fr',
        format: moment()['_locale']['_longDateFormat']['L']
    });
});

I dont like that, is there a clean way to get the format?

like image 976
Olivier Pons Avatar asked Dec 10 '15 23:12

Olivier Pons


People also ask

What is Moment () format?

Moment's format() method is what you use to convert a Moment object to a string. For example, here's how you would convert a YYYY-MM-DD string into a more human-readable format: const moment = require('moment'); const d = new Date('2019/06/01'); moment(d).format('MMMM d, YYYY'); // June 1, 2019.

Is MomentJS deprecated?

Moment construction falls back to js Date. This is discouraged and will be removed in an upcoming major release. This deprecation warning is thrown when no known format is found for a date passed into the string constructor.


Video Answer


1 Answers

You can retrieve locale-specific format strings with the longDateFormat() of the current localeData():

moment.locale('fr');

var localeData = moment.localeData();
var dateFormat = localeData.longDateFormat('LL');

console.log(dateFormat); // D MMMM YYYY
like image 152
Jonathan Lonowski Avatar answered Sep 22 '22 09:09

Jonathan Lonowski