Stéphane R. Stéphane R. - 2 months ago 16
Node.js Question

dateformat convert date string to isoDate

I would like convert date string to isoDate this node-dateformat module but i've error :


TypeError: Invalid date


My code :

let postProperties = {
dateCreated: dateFormat('4 juillet 1991', 'yyyy-mm-dd')
};


Any idea about this problem ?

Thank you :)

Answer

This is an i18n based date parsing issue. node-dateformat (and ultimately the core javascript date parsing it's relying on behind the scenes) can't handle French months. To verify this, try:

dateFormat('4 july 1991', 'yyyy-mm-dd')

This will work properly. If you want to parse French dates, I'd recommend using the awesome date/time library moment. Moment has full i18n support. You just have to add a custom locale bundle for your language, then you're all set. Here's a quick example showing how this can work with a French locale bundle:

import moment from 'moment';

// A French locale bundle; call this once in your code somewhere
moment.locale('fr', {
  months : "janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"),
  monthsShort : "janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"),
  weekdays : "dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"),
  weekdaysShort : "dim._lun._mar._mer._jeu._ven._sam.".split("_"),
  weekdaysMin : "Di_Lu_Ma_Me_Je_Ve_Sa".split("_"),
  longDateFormat : {
    LT : "HH:mm",
    LTS : "HH:mm:ss",
    L : "DD/MM/YYYY",
    LL : "D MMMM YYYY",
    LLL : "D MMMM YYYY LT",
    LLLL : "dddd D MMMM YYYY LT"
  },
  calendar : {
    sameDay: "[Aujourd'hui à] LT",
    nextDay: '[Demain à] LT',
    nextWeek: 'dddd [à] LT',
    lastDay: '[Hier à] LT',
    lastWeek: 'dddd [dernier à] LT',
    sameElse: 'L'
  },
  relativeTime : {
    future : "dans %s",
    past : "il y a %s",
    s : "quelques secondes",
    m : "une minute",
    mm : "%d minutes",
    h : "une heure",
    hh : "%d heures",
    d : "un jour",
    dd : "%d jours",
    M : "un mois",
    MM : "%d mois",
    y : "une année",
    yy : "%d années"
  },
  ordinalParse : /\d{1,2}(er|ème)/,
  ordinal : function (number) {
    return number + (number === 1 ? 'er' : 'ème');
  },
  meridiemParse: /PD|MD/,
  isPM: function (input) {
    return input.charAt(0) === 'M';
  },
  meridiem : function (hours, minutes, isLower) {
    return hours < 12 ? 'PD' : 'MD';
  },
  week : {
    dow : 1,
    doy : 4
  }
});

// Create a new moment instance, parsing your French date
const date = moment('4 juillet 1991', 'D MMMM YYYY')    

// Will output "1991-07-04"
console.log(date.format('YYYY-MM-DD'));