0

In JavaScript would it be possible to create a date using a format string?

Example:

new Date('10/12/2020', 'dd/mm/yyyy');

new Date('12/10/2020', 'mm/dd/yyyy');

new Date('2020/01/20', 'yyyy/mm/dd');

new Date('2020-01-20', 'yyyy-mm-dd');

new Date('2020 01 20', 'yyyy mm dd');

All of those would create a new valid date.

3
  • momentjs or Date.parse() Commented May 17, 2021 at 8:33
  • JavaScript's standard library doesn't have anything that does that, no. There are lots of date handling libraries out there (such as Moment) that do, though. @Justinas - No, Date.parse doesn't support a format string (or create a Date, come to that :-) ). Commented May 17, 2021 at 8:33
  • 1
    Don't use momentJS though. The project has been deprecated in favour of Luxon Commented May 17, 2021 at 8:38

2 Answers 2

1

Javascript does not support creating date with string format. You can use any of the following libraries for formatting,

  1. moment.js (https://momentjs.com/)

  2. Luxon(https://moment.github.io/luxon/)

  3. date-fns (https://date-fns.org/)

  4. Day.js (https://day.js.org/)

Example for moment.js :

  • moment().format('MMMM Do YYYY, h:mm:ss a');
  • moment(Your date).format('MM/DD/YYYY');
Sign up to request clarification or add additional context in comments.

Comments

0

Trying to parse a string using the Date constructor shouldn't be done. This can give you unpredictable results in different browser platforms.

The best is to use a popular date library like moment.js.

It is as easy as this.

moment(str, 'YYYY-MM-DD')

Here is the phrasing guide: https://momentjs.com/guides/#/parsing/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.