Parse

String + Date Format

Return the date parsed from date string using the given format string.

  1. // Moment.js
  2. moment('12-25-1995', 'MM-DD-YYYY');
  3. // => "1995-12-24T13:00:00.000Z"
  4. // Native
  5. const datePattern = /^(\d{2})-(\d{2})-(\d{4})$/;
  6. const [, month, day, year] = datePattern.exec('12-25-1995');
  7. new Date(`${month}, ${day} ${year}`);
  8. // => "1995-12-24T13:00:00.000Z"
  9. // date-fns
  10. import parse from 'date-fns/parse';
  11. parse('12-25-1995', 'MM-dd-yyyy', new Date());
  12. // => "1995-12-24T13:00:00.000Z"
  13. // dayjs
  14. dayjs('12-25-1995');
  15. // => "1995-12-24T13:00:00.000Z"
  16. // luxon
  17. DateTime.fromFormat('12-25-1995', 'MM-dd-yyyy').toJSDate();
  18. // => "1995-12-24T13:00:00.000Z"

String + Time Format

Return the date parsed from time string using the given format string.

  1. // Moment.js
  2. moment('2010-10-20 4:30', 'YYYY-MM-DD HH:mm');
  3. // => "2010-10-19T17:30:00.000Z"
  4. // Native
  5. const datePattern = /^(\d{4})-(\d{2})-(\d{2})\s(\d{1,2}):(\d{2})$/;
  6. const [, year, month, day, rawHour, min] = datePattern.exec('2010-10-20 4:30');
  7. new Date(`${year}-${month}-${day}T${('0' + rawHour).slice(-2)}:${min}:00`);
  8. // => "2010-10-19T17:30:00.000Z"
  9. // date-fns
  10. import parse from 'date-fns/parse';
  11. parse('2010-10-20 4:30', 'yyyy-MM-dd H:mm', new Date());
  12. // => "2010-10-19T17:30:00.000Z"
  13. // dayjs ⚠️ requires customParseFormat plugin
  14. import customParseFormat from 'dayjs/plugin/customParseFormat'
  15. dayjs.extend(customParseFormat)
  16. dayjs('2010-10-20 4:30', 'YYYY-MM-DD HH:mm');
  17. // => "2010-10-19T17:30:00.000Z"
  18. // luxon
  19. DateTime.fromFormat('2010-10-20 4:30', 'yyyy-MM-dd H:mm').toJSDate();
  20. // => "2010-10-19T17:30:00.000Z"

String + Format + locale

Return the date parsed from string using the given format string and locale.

  1. // Moment.js
  2. moment('2012 mars', 'YYYY MMM', 'fr');
  3. // => "2012-02-29T13:00:00.000Z"
  4. // date-fns
  5. import parse from 'date-fns/parse';
  6. import fr from 'date-fns/locale/fr';
  7. parse('2012 mars', 'yyyy MMMM', new Date(), { locale: fr });
  8. // => "2012-02-29T13:00:00.000Z"
  9. // dayjs ⚠️ requires customParseFormat plugin
  10. import customParseFormat from 'dayjs/plugin/customParseFormat'
  11. import 'dayjs/locale/fr'
  12. dayjs.extend(customParseFormat)
  13. dayjs('2012 mars', 'YYYY MMM', 'fr');
  14. // => "2012-02-29T13:00:00.000Z"
  15. // Luxon ❌ does not support Locale for node unless https://moment.github.io/luxon/docs/manual/install.html#node
  16. DateTime.fromFormat('2012 mars', 'yyyy MMMM', { locale: 'fr' });
  17. // => "2012-02-29T13:00:00.000Z"