Formatting JavaScript Dates
Working with dates and times can prove to be one of the most tedious and complex tasks for developers. While basic manipulation and date comparisons might be straightforward, anything beyond that often demands additional time and consideration. Fortunately, most programming languages and frameworks offer built-in APIs that streamline date and time operations.
JavaScript provides a built-in Date
object that allows you to easily manipulate date and time, but manipulation is only part of what we do. There comes a point when we need to format a Date
object to store its representation in a database or transmit it to another system, and JavaScript easily handles those situations. However, representing Date
objects with a custom format, a common requirement when displaying date and time to end users, poses a challenge.
In this tutorial, we will delve into the art of formatting JavaScript Date
objects into common formats, equipping you with valuable skills to tackle date and time-related challenges effectively.
Formatting as ISO
The International Organization for Standardization, commonly known as ISO, offers a widely used format for representing dates and times in a human- and machine-readable format. It is useful for various purposes, such as data transmission and storage, and it ensures a consistent and easily interpretable representation of dates and times across various systems and applications.
Following the ISO 8601 standard, the format appears as yyyy-mm-ddThh:mm:ss.sssZ
, where "T
" separates the date and time components, "sss
" indicates milliseconds, and "Z
" denotes Coordinated Universal Time (UTC). For example:
1 |
const date = new Date(2023, 5, 4, 13, 5, 34); |
2 |
const formattedString = date.toISOString(); |
3 |
console.log(formattedString); // output: 2023-06-04T18:05:34.000Z |
In this code, we create a Date
object representing 4 June 2023 at 1:05:34 PM (assuming the current time is in Central Daylight Time). By calling the toISOString()
method, we format the date and time into the ISO standard and store the resulting string in the formattedString
variable. When displayed in the console, the output showcases the date, time (converted to UTC), and milliseconds in ISO 8601 format. Do keep in mind that your outcomes may differ depending on your specific time zone.
Formatting Dates as yyyy-mm-dd
Another useful format is year-month-day, or yyyy-mm-dd
, and it is commonly used in databases, APIs, and various data exchange formats when the time component is not necessary. To achieve this format, you can extract the first ten characters from an ISO string. However, remember that toISOString()
formats the date in UTC, which may lead to unexpected results. To ensure predictable results, it is recommended that you extract the year, month, and day directly from a Date
object. This approach guarantees consistent and accurate representation without potential UTC-related issues. Consider the following code:
1 |
function formatYMD(date) { |
2 |
const year = date.getFullYear(); |
3 |
let month = date.getMonth() + 1; |
4 |
let day = date.getDate(); |
5 |
|
6 |
if (month < 10) { |
7 |
month = '0' + month; |
8 |
}
|
9 |
|
10 |
if (day < 10) { |
11 |
day = '0' + day; |
12 |
}
|
13 |
|
14 |
return `${year}-${month}-${day}`; |
15 |
}
|
This code defines a function called formatYMD()
that accepts a Date
object as input. Within the function, the first three lines extract the year
, month
, and day
values (it's important to note that months start at 0
in JavaScript's Date
object). The subsequent lines ensure that both the month
and day
values are represented as two digits by prepending a "0
" to single-digit numbers. The formatted parts are then joined with hyphens to compose the final yyyy-mm-dd
formatted string.
To use this function, you can simply pass it a Date
object, as the following example demonstrates:
1 |
const date = new Date(2023, 5, 4); // June 4, 2023 |
2 |
const output = formatYMD(date); |
3 |
console.log(output); // 2023-06-04 |
Formatting as mm/dd/yyyy and dd/mm/yyyy
It is essential to display dates in a format your users are accustomed to. While the formats mentioned earlier are human-readable, the mm/dd/yyyy
format is commonly used in the USA. To accommodate users expecting this format, we can write the following function:
1 |
function formatMDY(date) { |
2 |
const year = date.getFullYear(); |
3 |
let month = date.getMonth() + 1; |
4 |
let day = date.getDate(); |
5 |
|
6 |
if (month < 10) { |
7 |
month = '0' + month; |
8 |
}
|
9 |
|
10 |
if (day < 10) { |
11 |
day = '0' + day; |
12 |
}
|
13 |
|
14 |
return `${month}/${day}/${year}`; |
15 |
}
|
This code defines the formatMDY()
function, which shares a similar approach to the formatYMD()
function discussed in the previous section. The beginning of the function extracts the date values and normalizes the month
and day
values into two-character strings. The function concatenates the date components using slashes, resulting in the mm/dd/yyyy
formatted string.
Most other countries use a dd/mm/yyyy
format, and we can accommodate those users with a similar function shown below:
1 |
function formatDMY(date) { |
2 |
const year = date.getFullYear(); |
3 |
let month = date.getMonth() + 1; |
4 |
let day = date.getDate(); |
5 |
|
6 |
if (month < 10) { |
7 |
month = '0' + month; |
8 |
}
|
9 |
|
10 |
if (day < 10) { |
11 |
day = '0' + day; |
12 |
}
|
13 |
|
14 |
return `${day}/${month}/${year}`; |
15 |
}
|
Once again, this function adheres to the same approach as the previous examples. However, the distinction lies in the output. Here, we concatenate the day
, month
, and year
using slashes to result in the dd/mm/yyyy
formatted string.
Formatting Time
Unlike formatting dates, formatting time is relatively consistent across the globe. The majority of countries employ the hh:mm
format, although some use a 12-hour clock, while others adhere to a 24-hour clock. Fortunately, we can accommodate both formats with the following function:
1 |
function formatTime(date, clockType = 24) { |
2 |
let hours = date.getHours(); |
3 |
let minutes = date.getMinutes(); |
4 |
let amPm = ''; |
5 |
|
6 |
if (clockType === 12) { |
7 |
amPm = 'AM'; |
8 |
if (hours > 12) { |
9 |
hours = hours - 12; |
10 |
amPm = 'PM'; |
11 |
} else if (hours === 0) { |
12 |
hours = 12; |
13 |
}
|
14 |
}
|
15 |
|
16 |
if (hours < 10) { |
17 |
hours = '0' + hours; |
18 |
}
|
19 |
|
20 |
if (minutes < 10) { |
21 |
minutes = '0' + minutes; |
22 |
}
|
23 |
|
24 |
return `${hours}:${minutes}${amPm}`; |
25 |
}
|
This code introduces the formatTime()
function, which accepts two parameters: a JavaScript Date object and a numeric value indicating whether the time should be formatted in 12-hour (AM/PM) or the default 24-hour format.
The beginning of the function extracts the hours and minutes from the given Date
object by using the getHours()
and getMinutes()
methods respectively. It initializes the amPm
variable as an empty string, which will later hold the AM/PM indicator for the 12-hour format. For the 24-hour format, the amPm
variable remains an empty string.
The function then checks if the clockType
parameter is set to 12
. If true, it proceeds to prepare the hours
and amPm
variables for the 12-hour format. It checks if the hours
value is greater than 12
, indicating afternoon or evening. If so, it subtracts 12 from hours
and sets the amPm
variable to 'PM'. In the case where hours is 0
(midnight), it sets hours to 12
to represent 12 AM. For morning hours (1 AM to 11 AM), the function leaves hours
unchanged as it already represents the correct time.
Next, the function ensures that both hours
and minutes
are represented as two digits by padding them with a leading zero if needed. This allows for consistent formatting. The function then concatenates them with a colon (:
) and the amPm
variable to produce the final formatted time string.
You can use formatTime()
like this:
1 |
const date = new Date(); |
2 |
const time24 = formatTime(date); |
3 |
const time12 = formatTime(date, 12); |
4 |
|
5 |
console.log(time24); // hh:mm |
6 |
console.log(time12); // hh:mmAM or hh:mmPM |
Conclusion
Formatting dates and times is a common requirement in JavaScript development, but the built-in formatting capabilities of the Date object have their limitations. We often find ourselves responsible for implementing our own custom formatting solutions. Whether it's displaying dates in yyyy-mm-dd
or mm/dd/yyyy
formats or formatting time in another custom format, the Date
object's methods become indispensable tools.