How to Format a Date in JavaScript
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:
1 | const date = new Date('July 22, 2018 07:22:13'); |
The built-in methods provide various string representations:
1 | date.toString(); // "Sun Jul 22 2018 07:22:13 GMT+0200 (Central European Summer Time)" |
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:
1 | date.getDate(); // 22 |
There are also equivalent UTC versions of these methods, which return the UTC value instead of the values adjusted to the current timezone:
1 | date.getUTCDate(); // 22 |
By using these methods, you can easily format dates in JavaScript according to your specific requirements.
tags: [“date formatting”, “JavaScript”, “programming”]