Formatting dates in JavaScript is a common task. There are several methods available to generate a string representation of a date object. Let’s explore the different options:
Given a Date
object:
const date = new Date('July 22, 2018 07:22:13');
The built-in methods provide various string representations:
date.toString(); // "Sun Jul 22 2018 07:22:13 GMT+0200 (Central European Summer Time)"
date.toTimeString(); // "07:22:13 GMT+0200 (Central European Summer Time)"
date.toUTCString(); // "Sun, 22 Jul 2018 05:22:13 GMT"
date.toDateString(); // "Sun Jul 22 2018"
date.toISOString(); // "2018-07-22T05:22:13.000Z" (ISO 8601 format)
date.toLocaleString(); // "22/07/2018, 07:22:13"
date.toLocaleTimeString(); // "07:22:13"
However, you are not limited to these built-in methods. JavaScript provides lower-level methods to extract specific values from a date and construct custom representations:
date.getDate(); // 22
date.getDay(); // 0 (0 represents Sunday, 1 represents Monday, and so on)
date.getFullYear(); // 2018
date.getMonth(); // 6 (index starts from 0)
date.getHours(); // 7
date.getMinutes(); // 22
date.getSeconds(); // 13
date.getMilliseconds(); // 0 (not specified)
date.getTime(); // 1532236933000
date.getTimezoneOffset(); // -120 (varies depending on the location and time of check - represents the timezone difference in minutes)
There are also equivalent UTC versions of these methods, which return the UTC value instead of the values adjusted to the current timezone:
date.getUTCDate(); // 22
date.getUTCDay(); // 0 (0 represents Sunday, 1 represents Monday, and so on)
date.getUTCFullYear(); // 2018
date.getUTCMonth(); // 6 (index starts from 0)
date.getUTCHours(); // 5 (differs from the previous example)
date.getUTCMinutes(); // 22
date.getUTCSeconds(); // 13
date.getUTCMilliseconds(); // 0 (not specified)
By using these methods, you can easily format dates in JavaScript according to your specific requirements.