JavaScript Date Formatting Guide: How to Format Dates Properly with Examples

目次

1. Introduction: Why Date Formatting Matters in JavaScript

In web development using JavaScript, displaying and managing dates and times is essential. For example, calendar applications and log management systems require date and time data to be formatted correctly. However, date handling in JavaScript can feel a bit complex for beginners.

In this guide, we introduce practical techniques and code examples to help you master date formatting in JavaScript. From basic usage of the Date object to advanced use of Intl.DateTimeFormat, and even comparisons of external libraries, this article provides a comprehensive explanation.

Common Scenarios Where Date Formatting Is Required

  1. Data display in web applications:
  • Supporting users across different calendars and time zones.
  1. Log management and debugging:
  • Recording timestamps for error logs and user actions.
  1. Multilingual support:
  • Adjusting date display formats for international users.

Benefits for Readers

By reading this guide, you will gain the following skills:

  • Understanding how to work with the basic Date object.
  • Flexible date display using manual formatting and built-in methods.
  • Efficient coding with the help of external date libraries.

In the next section, we will take a closer look at the fundamentals of the JavaScript Date object. Understanding this will allow you to smoothly move on to more advanced topics later.

2. Basics of Date Handling in JavaScript: What Is the Date Object?

In JavaScript, the Date object is used to manage dates and times. Understanding this object is the first step toward handling date formatting correctly. This section explains the basic usage of the Date object.

2.1 How to Create a Date Object

A Date object can be created in the following ways.

  1. Get the current date and time
const today = new Date();
console.log(today); // Outputs the current date and time
  1. Set a specific date and time
const customDate = new Date(2024, 11, 28); // Year, month (starts from 0), day
console.log(customDate); // December 28, 2024
  1. Create a date from a string
const dateFromString = new Date('2024-12-28');
console.log(dateFromString); // Date converted from ISO format
  1. Create a date from a timestamp
const timestampDate = new Date(1703740800000); // Milliseconds
console.log(timestampDate); // Date represented by the timestamp

2.2 Methods for Retrieving Date and Time Components

The Date object provides methods to retrieve individual date and time components.

MethodDescriptionExample Output
getFullYear()Gets the year2024
getMonth()Gets the month (starts from 0)11 (December)
getDate()Gets the day of the month28
getDay()Gets the day of the week (0 = Sunday, 6 = Saturday)6 (Saturday)

2.3 Working with Time Zones and UTC

Get local time:

const date = new Date();
console.log(date.toString()); // Local time

Get UTC time:

console.log(date.toUTCString()); // UTC-based time

Get time zone offset:

console.log(date.getTimezoneOffset()); // -540 (in minutes, for Japan Standard Time)

Summary

In this section, we explained the basics of the Date object in JavaScript, including how to create dates and retrieve or manipulate date components.

In the next section, we will dive deeper into specific methods for formatting dates in JavaScript.

3. Three Ways to Format Dates in JavaScript

JavaScript provides several ways to format dates into different representations. In this section, we explain three approaches in detail: manual formatting, built-in methods, and advanced formatting options.

3.1 Manual Formatting: From Basics to Practical Use

Simple Custom Format Example

const date = new Date();
const year = date.getFullYear(); // Year
const month = ('0' + (date.getMonth() + 1)).slice(-2); // Month (zero-padded)
const day = ('0' + date.getDate()).slice(-2); // Day (zero-padded)

const formattedDate = `${year}-${month}-${day}`;
console.log(formattedDate); // Example: 2024-12-28

3.2 Locale-Aware Formatting with toLocaleDateString()

Basic Usage

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

Customization with Options

const options = { year: 'numeric', month: '2-digit', day: '2-digit' };
console.log(date.toLocaleDateString('ja-JP', options)); // Example: 2024/12/28

3.3 Advanced Customization: Using Intl.DateTimeFormat

Basic Usage

const date = new Date();
const formatter = new Intl.DateTimeFormat('ja-JP', { dateStyle: 'full' });
console.log(formatter.format(date)); // Example: Saturday, December 28, 2024

Summary

In this section, we introduced three different ways to format dates in JavaScript. In the next section, we will explain how to improve efficiency by using external libraries for date handling.

4. Using External Libraries: Comparing Moment.js, date-fns, and Day.js

While JavaScript’s built-in date methods are powerful, using external libraries can make complex formatting and processing more concise and efficient.

4.1 Moment.js: A Proven Library for Legacy Systems

Basic Usage

const moment = require('moment'); // Import in a Node.js environment
const now = moment(); // Current date and time
console.log(now.format('YYYY-MM-DD HH:mm:ss')); // Example: 2024-12-28 14:30:45

4.2 date-fns: A Modular Library for Modern Projects

Basic Usage

import { format, addDays } from 'date-fns';

const now = new Date();
console.log(format(now, 'yyyy-MM-dd')); // Example: 2024-12-28

const nextWeek = addDays(now, 7);
console.log(format(nextWeek, 'yyyy-MM-dd')); // Example: 2025-01-04

4.3 Day.js: A Lightweight, Moment-Compatible Modern Library

Basic Usage

const dayjs = require('dayjs');

const now = dayjs();
console.log(now.format('YYYY-MM-DD')); // Example: 2024-12-28

const nextWeek = now.add(7, 'day');
console.log(nextWeek.format('YYYY-MM-DD')); // Example: 2025-01-04

4.4 Library Comparison Table

LibraryFeaturesFile SizeRecommended Use
Moment.jsFeature-rich and widely adopted~300KBMaintaining legacy systems
date-fnsModular, lightweight, modern JavaScript support~25KBModern projects and lightweight environments
Day.jsLightweight, Moment-compatible, extensible via plugins~2KBFast and lightweight front-end development

Summary

In this section, we compared popular external libraries that simplify date handling in JavaScript. In the next section, we will introduce practical application examples using these formatting techniques.

5. Practical Examples: Applications Using Date Formatting

5.1 Displaying Dates in a Calendar Application

Implementation Example

const selectedDate = new Date(); // Date selected by the user

const formattedDate = selectedDate.toLocaleDateString('ja-JP', {
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  weekday: 'long'
});

console.log(`Selected date: ${formattedDate}`); 
// Example: Selected date: Saturday, December 28, 2024

5.2 Managing Timestamps in Log Files

Implementation Example

const logTime = new Date().toISOString(); // Get date and time in ISO format
console.log(`[LOG] ${logTime}: Process started`);
// Example: [LOG] 2024-12-28T05:30:00.000Z: Process started

5.3 Validating and Formatting Form Input Dates

Implementation Example

function formatInputDate(inputDate) {
  const date = new Date(inputDate); // Convert input string to a Date object

  if (isNaN(date)) {
    console.log('Invalid date format.');
    return null;
  }

  return date.toLocaleDateString('ja-JP', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
}

console.log(formatInputDate('2024-12-28')); // Example: 2024/12/28

Summary

In this section, we introduced practical examples of using date formatting in JavaScript, including calendar displays, log management, and form validation. In the next section, we address frequently asked questions (FAQ) and provide solutions to common issues.

6. Frequently Asked Questions (FAQ)

Q1: How can I display dates and times in ISO format?

Answer

ISO format is an international standard for date and time representation and is widely used in databases and API communications. In JavaScript, you can use the toISOString() method of the Date object.

Sample Code

const date = new Date();
console.log(date.toISOString()); // Example: 2024-12-28T05:30:00.000Z

Q2: How should I handle the difference between UTC time and local time?

Answer

By default, JavaScript uses local time, but it also provides methods to convert to and from UTC.

Sample Code

Convert local time to UTC:

const date = new Date();
console.log(date.toUTCString()); // Example: Sat, 28 Dec 2024 05:30:00 GMT

Convert UTC to local time:

const date = new Date('2024-12-28T05:30:00Z'); 
console.log(date.toString()); 
// Example: Sat Dec 28 2024 14:30:00 GMT+0900 (Japan Standard Time)

Q3: What is the easiest way to handle zero padding in date formatting?

Answer

function zeroPad(number) {
  return number.toString().padStart(2, '0');
}

const date = new Date();
const formattedDate = `${date.getFullYear()}-${zeroPad(date.getMonth() + 1)}-${zeroPad(date.getDate())}`;
console.log(formattedDate); // Example: 2024-12-28

Summary

In this section, we covered frequently asked questions about date formatting in JavaScript and provided practical solutions. In the next section, we will conclude the article with a summary and an action plan for applying what you have learned.

7. Conclusion and Practical Next Steps

7.1 Key Takeaways from This Article

  1. JavaScript Date Object Basics: We covered how to create Date objects and use methods to retrieve and manipulate date and time values.
  2. Three Date Formatting Approaches: Manual formatting, built-in methods, and the use of external libraries.
  3. Practical Use Cases: Real-world examples such as calendars, log management, and form validation.
  4. FAQ: Common challenges and proven solutions for date formatting.

7.2 Action Plan for Practical Implementation

  1. Try the Code Examples: Run the sample code in an online editor or your local development environment to deepen your understanding.
  2. Apply to Real Projects: Integrate date formatting into actual projects by adding calendar features or log management functionality.
  3. Compare Libraries: Test Moment.js, date-fns, and Day.js to determine which best fits your project requirements.

7.3 Final Thoughts

JavaScript date formatting ranges from simple operations to advanced customization and powerful external libraries. Use this guide as a reference to implement efficient, flexible, and maintainable date handling in your applications.

広告