How to format a JavaScript date
Posted By: Anonymous
In JavaScript, how can I format a date object to print as 10-Aug-2010
?
Solution
For custom-delimited date formats, you have to pull out the date (or time)
components from a DateTimeFormat
object (which is part of the
ECMAScript Internationalization API), and then manually create a string
with the delimiters you want.
To do this, you can use DateTimeFormat#formatToParts
. You could
destructure the array, but that is not ideal, as the array output depends on the
locale:
// example 1
const o_date_en = new Intl.DateTimeFormat('en');
const a_date_en = o_date_en.formatToParts();
// example 2
const o_date_hi = new Intl.DateTimeFormat('hi');
const a_date_hi = o_date_hi.formatToParts();
// print
console.log(a_date_en, a_date_hi);
Better would be to reduce the array into an object:
const o_date = new Intl.DateTimeFormat;
const f_date = (m_ca, m_it) => Object({...m_ca, [m_it.type]: m_it.value});
const m_date = o_date.formatToParts().reduce(f_date, {});
console.log(m_date.day + '-' + m_date.month + '-' + m_date.year);
You can also pull out the parts of a DateTimeFormat
one-by-one using
DateTimeFormat#format
, but note that when using this method, as of March
2020, 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).
const d = new Date(2010, 7, 5);
const ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(d);
const mo = new Intl.DateTimeFormat('en', { month: 'short' }).format(d);
const da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(d);
console.log(`${da}-${mo}-${ye}`);
When working with dates and times, it is usually worth using a library (eg.
moment.js, luxon) 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).
Answered By: Anonymous
Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.