0

Formatting JavaScript Dates

 1 year ago
source link: https://code.tutsplus.com/formatting-javascript-dates--cms-107619t
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Formatting JavaScript Dates

Jeremy McPeak Last updated Jul 30, 2023

Read Time: 7 min

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:

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 June 4th, 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 expected 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:

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
    if (day < 10) {
        day = '0' + day;
    }
    return `${year}-${month}-${day}`;
}

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 next 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, like the following example demonstrates:

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 end-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:

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
    if (day < 10) {
        day = '0' + day;
    }
    return `${month}/${day}/${year}`;
}

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:

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
    if (day < 10) {
        day = '0' + day;
    }
    return `${day}/${month}/${year}`;
}

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:

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;
            amPm = 'PM';
        } else if (hours === 0) {
            hours = 12;
        }
    }
    if (hours < 10) {
        hours = '0' + hours;
    }
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:

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
Advertisement

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, mm/dd/yyyy, or formatting time in another custom format, the Date object's methods become indispensable tools.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK