How do I format a Javascript Date object as a string? (Preferably in the format: 10-Aug-2010)
How do I format a Javascript Date object as a string? (Preferably in the
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
For custom-delimited date formats, you have to pull out the date (or time)
components from a
DateTimeFormatobject (which is part of theECMAScript Internationalization API), and then manually create a string
with the delimiters you want.
To do this, you can use
DateTimeFormat#formatToParts. You coulddestructure the array, but that is not ideal, as the array output depends on the
locale:
Better would be to map a format array to resultant strings:
You can also pull out the parts of a
DateTimeFormatone-by-one usingDateTimeFormat#format, but note that when using this method, as of March2020, there is a bug in the ECMAScript implementation when it comes to
leading zeros on minutes and seconds (this bug is circumvented by the approach
above).
When working with dates and times, it is usually worth using a library (eg. luxon, date-fns,
moment.jsis not recommended for new projects) because of the many hidden complexities of the field.Note that the ECMAScript Internationalization API, used in the solutions above
is not supported in IE10 (0.03% global browser market share in Feb
2020).