目次

1. Introduction

When working with JavaScript, you will frequently encounter situations that require handling dates. For example, displaying the current date on a website or managing event schedules. Although JavaScript date formatting may look simple at first glance, many beginners find it confusing in practice.

In this article, we will clearly explain JavaScript date formatting, from the basics to more advanced techniques. By reading this guide, you will gain the following knowledge:

  • Basic date operations using the JavaScript Date object
  • Date formatting methods using built-in APIs such as toLocaleDateString() and Intl.DateTimeFormat
  • An introduction to useful libraries that help streamline date formatting

This article is designed to help beginners start with the fundamentals, while also providing intermediate users with practical techniques and library usage tips. By doing so, you will be able to acquire skills that are useful in real-world development.

In the next section, we will begin by reviewing the fundamentals of the JavaScript Date object. Understanding these basics will allow you to gain a deeper insight into how date formatting works.

2. Fundamentals | Basic Date Handling in JavaScript

JavaScript provides the Date object for handling dates and times. By using this object, you can retrieve the current date and time, specify a particular date, and perform flexible operations such as adding or subtracting time.

2.1 Creating Date Objects

1. Getting the Current Date and Time

const today = new Date();
console.log(today); // Example output: Sun Dec 29 2024 14:30:00 GMT+0900 (JST)

2. Specifying a Specific Date

const specificDate = new Date(2024, 11, 29); // Year, month (0-based), day
console.log(specificDate); // Example output: Sun Dec 29 2024 00:00:00 GMT+0900 (JST)

3. Creating a Date from a Timestamp

const timestampDate = new Date(1703827200000); // Timestamp
console.log(timestampDate); // Example output: Sun Dec 29 2024 00:00:00 GMT+0900 (JST)

2.2 Retrieving Date Components

1. Getting the Year, Month, and Day

const today = new Date();
console.log(today.getFullYear()); // Get year: 2024
console.log(today.getMonth() + 1); // Get month (0-based): 12
console.log(today.getDate()); // Get day: 29

2.3 Editing and Manipulating Dates

1. Adding Days to a Date

today.setDate(today.getDate() + 1);
console.log(today); // Displays the next day's date

2. Changing to a Specific Date

today.setFullYear(2025); // Change year to 2025
today.setMonth(0); // Change month to January
today.setDate(1); // Change day to the 1st
console.log(today); // Example output: Wed Jan 1 2025 14:30:00 GMT+0900 (JST)

2.4 Time Zones and UTC

1. Retrieving UTC Date Values

console.log(today.getUTCFullYear()); // Get UTC year
console.log(today.getUTCMonth() + 1); // Get UTC month
console.log(today.getUTCDate()); // Get UTC day

2. Getting an ISO 8601 Date String

console.log(today.toISOString()); // Get ISO 8601 formatted string

Summary

In this section, we explained the fundamentals of date manipulation using the JavaScript Date object.

3. Date Formatting Methods [Basic]

When working with dates in JavaScript, customizing the display format is extremely important. In this section, we will explain the basic date formatting methods.

3.1 Simple String Concatenation

1. Displaying Dates in YYYY-MM-DD Format

const today = new Date();
const year = today.getFullYear();
const month = ('0' + (today.getMonth() + 1)).slice(-2);
const day = ('0' + today.getDate()).slice(-2);
const formattedDate = `${year}-${month}-${day}`;
console.log(formattedDate); // Example output: 2024-12-29

3.2 Formatting with toLocaleDateString()

const date = new Date();
console.log(date.toLocaleDateString('ja-JP')); // Example output: 2024/12/29

3.3 ISO 8601 Format and toISOString()

console.log(date.toISOString());
// Example output: 2024-12-29T05:30:00.000Z

Summary

In this section, we covered the basics of date formatting in JavaScript.

4. Advanced Date Formatting [Practical]

In this section, we will introduce more advanced and practical date formatting techniques.

4.1 Custom Formatting with Intl.DateTimeFormat

const date = new Date();
const formatter = new Intl.DateTimeFormat('ja-JP', {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit'
});
console.log(formatter.format(date)); // Example output: 2024/12/29

4.2 Handling Time Zones

const utcDate = new Date(Date.UTC(2024, 11, 29, 12, 0, 0));
const formatter = new Intl.DateTimeFormat('en-US', {
  timeZone: 'America/New_York',
  timeZoneName: 'short'
});
console.log(formatter.format(utcDate));
// Example output: 12/29/2024, EST

Summary

In this section, we introduced advanced date formatting techniques suitable for real-world applications.

5. Useful External Libraries for Date Formatting

JavaScript provides many built-in features for date manipulation, but using external libraries can significantly improve efficiency and readability.

5.1 Using Moment.js (Deprecated)

const moment = require('moment');
const formattedDate = moment().format('YYYY-MM-DD HH:mm:ss');
console.log(formattedDate); // Example output: 2024-12-29 14:30:00

5.2 Why date-fns Is Recommended and Example Usage

import { format } from 'date-fns';
const today = new Date();
const formattedDate = format(today, 'yyyy-MM-dd HH:mm:ss');
console.log(formattedDate); // Example output: 2024-12-29 14:30:00

Summary

In this section, we introduced the benefits of external libraries and how to use them effectively.

6. Common Errors and Solutions [FAQ]

When working with dates in JavaScript, both beginners and intermediate developers often encounter similar errors and issues. In this section, we explain common problems, their causes, and practical solutions in an FAQ format.

Q1. Why does the month shift by one?

Problem Example

const date = new Date(2024, 12, 29);
console.log(date); // Output: 2025-01-29

Cause

In JavaScript, month indexes start from 0, not 1.

Solution

When specifying a month, subtract 1 from the desired month value.

const date = new Date(2024, 11, 29); // Correct way to specify December
console.log(date); // Output: 2024-12-29

Q2. Why are numbers not zero-padded?

Problem Example

const today = new Date();
const month = today.getMonth() + 1; // 12
const day = today.getDate();       // 9
console.log(`${today.getFullYear()}-${month}-${day}`);
// Output: 2024-12-9

Solution

Use slice() or padStart() to apply zero-padding.

const month = ('0' + (today.getMonth() + 1)).slice(-2);
const day = ('0' + today.getDate()).slice(-2);
console.log(`${today.getFullYear()}-${month}-${day}`);
// Output: 2024-12-09

Summary

In this section, we explained common errors and important considerations related to date handling in JavaScript using an FAQ format.

7. Important Notes and Best Practices

Date handling in JavaScript is powerful, but misunderstandings of its specifications or improper usage can easily lead to errors and bugs. In this section, we introduce important notes and best practices for safe and efficient date manipulation.

7.1 Month Indexes and Zero Padding

const date = new Date(2024, 11, 29); // December 29
console.log(date.getMonth() + 1); // Output: 12

7.2 Time Zone Management

Using UTC

const utcDate = new Date(Date.UTC(2024, 11, 29, 12, 0, 0));
console.log(utcDate.toISOString());
// Output: 2024-12-29T12:00:00.000Z

7.3 Improving Readability and Maintainability

Creating a Date Formatting Function

function formatDate(date) {
  const year = date.getFullYear();
  const month = ('0' + (date.getMonth() + 1)).slice(-2);
  const day = ('0' + date.getDate()).slice(-2);
  return `${year}-${month}-${day}`;
}
console.log(formatDate(new Date()));
// Output: 2024-12-29

Summary

In this section, we explained important notes and best practices for handling dates in JavaScript.

8. Conclusion

Date handling in JavaScript is a frequently required feature in web development. In this article, we explained everything step by step, from basic concepts to advanced techniques, enabling readers to acquire knowledge that can be applied in real-world projects.

Review of Key Learnings

  1. Basic Date Operations
  • Explained fundamental operations and important considerations when using the Date object.
  1. Fundamentals and Advanced Formatting Techniques
  • Introduced custom formatting, internationalization support, and time zone handling.
  1. Using External Libraries
  • Compared features and usage of libraries such as date-fns and Day.js.
  1. Common Errors and Solutions
  • Organized typical error cases and their solutions in an FAQ format.

Next Steps

  1. Try the sample code in your own environment.
  2. Introduce libraries and perform comparisons.
  3. Challenge yourself with practical applications in real systems.

Final Thoughts

JavaScript date handling can become complex when considering detailed specifications and internationalization. Use this article as a reference to further refine your practical skills.

広告