JavaでLocalDateを使って現在の日付と次の日付を取得する方法

JavaJavaBeginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

Introduction

This tutorial will guide you through retrieving the current date and calculating the next date using the LocalDate class in Java. The Java Time API, introduced in Java 8, provides comprehensive date and time handling capabilities. By the end of this tutorial, you will understand how to use LocalDate to perform basic date operations efficiently.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["Object-Oriented and Advanced Concepts"]) java(("Java")) -.-> java/SystemandDataProcessingGroup(["System and Data Processing"]) java/ObjectOrientedandAdvancedConceptsGroup -.-> java/date("Date") java/SystemandDataProcessingGroup -.-> java/object_methods("Object Methods") subgraph Lab Skills java/date -.-> lab-414036{{"JavaでLocalDateを使って現在の日付と次の日付を取得する方法"}} java/object_methods -.-> lab-414036{{"JavaでLocalDateを使って現在の日付と次の日付を取得する方法"}} end

Understanding the Java Time API and LocalDate

Before we start coding, let us learn about the LocalDate class and why it is useful for handling dates in Java applications.

What is the Java Time API?

Java 8 introduced the Java Time API in the java.time package to address the limitations of older date and time classes. This API provides a clearer and more intuitive approach to date and time handling.

Introduction to LocalDate

The LocalDate class represents a date without a time component (year, month, day). It is immutable, thread-safe, and follows the ISO-8601 calendar system.

Some key advantages of using LocalDate include:

  • It provides clear separation between date, time, and date-time concepts
  • It offers intuitive methods for date manipulation
  • It has built-in support for different date formats
  • It handles date calculations correctly

Let us create a new Java file to explore LocalDate functionality.

  1. In the WebIDE, click on the Explorer panel (the icon that looks like pages on the left sidebar)
  2. Right-click in the file explorer panel and select "New File"
  3. Name the file DateExample.java and click "OK"
  4. Copy the following basic code template into the file:
public class DateExample {
    public static void main(String[] args) {
        // We will add our date code here
        System.out.println("Learning about LocalDate in Java");
    }
}
  1. Save the file by pressing Ctrl+S or selecting File > Save from the menu

Now that we have created our Java file, we will proceed to add code to work with the current date in the next step.

Retrieving the Current Date with LocalDate

In this step, we will modify our Java program to retrieve and display the current date using the LocalDate class.

Importing the LocalDate Class

First, we need to import the LocalDate class from the java.time package. Open the DateExample.java file and add the import statement at the top:

import java.time.LocalDate;

public class DateExample {
    public static void main(String[] args) {
        // We will add our date code here
        System.out.println("Learning about LocalDate in Java");
    }
}

Using LocalDate.now() Method

The LocalDate class provides a static method called now() that returns the current date. Let us modify our code to retrieve and display the current date:

import java.time.LocalDate;

public class DateExample {
    public static void main(String[] args) {
        // Get the current date
        LocalDate currentDate = LocalDate.now();

        // Display the current date
        System.out.println("Current date: " + currentDate);
    }
}

Compiling and Running the Program

Now, let us compile and run our program:

  1. Open a terminal in the WebIDE (Terminal > New Terminal from the menu)
  2. Navigate to the project directory if needed:
    cd /home/labex/project
  3. Compile the Java program:
    javac DateExample.java
  4. Run the compiled program:
    java DateExample

You should see output similar to:

Current date: 2023-04-12

The actual date will reflect the current date when you run the program.

Understanding the Output Format

The default string representation of a LocalDate object follows the ISO-8601 format: YYYY-MM-DD. This is an international standard for representing dates.

For example, 2023-04-12 represents April 12, 2023.

You have successfully retrieved and displayed the current date using the LocalDate class. In the next step, we will learn how to calculate the next date.

Calculating the Next Date

Now that we can retrieve the current date, we will learn how to calculate the next date by adding days to a LocalDate object.

Understanding Date Manipulation with LocalDate

The LocalDate class provides several methods for date manipulation, including:

  • plusDays(long days): Adds the specified number of days
  • plusWeeks(long weeks): Adds the specified number of weeks
  • plusMonths(long months): Adds the specified number of months
  • plusYears(long years): Adds the specified number of years

There are also corresponding minus methods for subtraction.

Let us enhance our code to calculate and display the next date:

import java.time.LocalDate;

public class DateExample {
    public static void main(String[] args) {
        // Get the current date
        LocalDate currentDate = LocalDate.now();

        // Calculate the next date by adding one day
        LocalDate nextDate = currentDate.plusDays(1);

        // Display both dates
        System.out.println("Current date: " + currentDate);
        System.out.println("Next date: " + nextDate);
    }
}

Compiling and Running the Updated Program

Let us compile and run our updated program:

  1. Make sure you have saved the changes to DateExample.java
  2. In the terminal, compile the Java program:
    javac DateExample.java
  3. Run the compiled program:
    java DateExample

You should see output similar to:

Current date: 2023-04-12
Next date: 2023-04-13

Again, the actual dates will reflect the current date when you run the program.

Exploring Other Date Manipulations

Let us further enhance our program to demonstrate other date manipulation methods:

import java.time.LocalDate;

public class DateExample {
    public static void main(String[] args) {
        // Get the current date
        LocalDate currentDate = LocalDate.now();

        // Calculate various future dates
        LocalDate nextDate = currentDate.plusDays(1);
        LocalDate nextWeek = currentDate.plusWeeks(1);
        LocalDate nextMonth = currentDate.plusMonths(1);
        LocalDate nextYear = currentDate.plusYears(1);

        // Display all dates
        System.out.println("Current date: " + currentDate);
        System.out.println("Next date: " + nextDate);
        System.out.println("Date after one week: " + nextWeek);
        System.out.println("Date after one month: " + nextMonth);
        System.out.println("Date after one year: " + nextYear);
    }
}

Compile and run the program again:

javac DateExample.java
java DateExample

The output will show the current date, the next date, and dates after one week, one month, and one year:

Current date: 2023-04-12
Next date: 2023-04-13
Date after one week: 2023-04-19
Date after one month: 2023-05-12
Date after one year: 2024-04-12

Important Concept: Immutability

Notice that we assigned the result of plusDays() to a new variable. This is because LocalDate objects are immutable, meaning their values cannot be changed after creation. Methods like plusDays() do not modify the original object; instead, they return a new object with the updated value.

This immutability is an important feature that makes LocalDate objects thread-safe and more predictable in complex applications.

Extracting Date Components

In this step, we will learn how to extract individual components from a LocalDate object, such as the day, month, year, and day of the week.

Date Component Extraction Methods

The LocalDate class provides several methods to extract specific components of a date:

  • getDayOfMonth(): Returns the day of the month (1-31)
  • getMonthValue(): Returns the month as a number (1-12)
  • getMonth(): Returns the month as an enum constant
  • getYear(): Returns the year
  • getDayOfWeek(): Returns the day of the week as an enum constant

Let us create a new file to explore these methods:

  1. In the WebIDE, create a new file named DateComponents.java
  2. Add the following code to the file:
import java.time.LocalDate;
import java.time.Month;
import java.time.DayOfWeek;

public class DateComponents {
    public static void main(String[] args) {
        // Get the current date
        LocalDate currentDate = LocalDate.now();

        // Extract date components
        int day = currentDate.getDayOfMonth();
        int monthValue = currentDate.getMonthValue();
        Month month = currentDate.getMonth();
        int year = currentDate.getYear();
        DayOfWeek dayOfWeek = currentDate.getDayOfWeek();

        // Display the components
        System.out.println("Current date: " + currentDate);
        System.out.println("Day of month: " + day);
        System.out.println("Month (number): " + monthValue);
        System.out.println("Month (name): " + month);
        System.out.println("Year: " + year);
        System.out.println("Day of week: " + dayOfWeek);
    }
}
  1. Save the file by pressing Ctrl+S

Compiling and Running the Program

Now, let us compile and run our new program:

  1. In the terminal, compile the Java program:
    javac DateComponents.java
  2. Run the compiled program:
    java DateComponents

You should see output similar to:

Current date: 2023-04-12
Day of month: 12
Month (number): 4
Month (name): APRIL
Year: 2023
Day of week: WEDNESDAY

Creating a Specific Date

In addition to getting the current date, we can create a LocalDate object representing a specific date using the of() method. Let us enhance our program to create a specific date:

import java.time.LocalDate;
import java.time.Month;
import java.time.DayOfWeek;

public class DateComponents {
    public static void main(String[] args) {
        // Get the current date
        LocalDate currentDate = LocalDate.now();

        // Create a specific date
        LocalDate specificDate = LocalDate.of(2025, 12, 25);

        // Extract date components from the current date
        int day = currentDate.getDayOfMonth();
        int monthValue = currentDate.getMonthValue();
        Month month = currentDate.getMonth();
        int year = currentDate.getYear();
        DayOfWeek dayOfWeek = currentDate.getDayOfWeek();

        // Display the current date components
        System.out.println("Current date: " + currentDate);
        System.out.println("Day of month: " + day);
        System.out.println("Month (number): " + monthValue);
        System.out.println("Month (name): " + month);
        System.out.println("Year: " + year);
        System.out.println("Day of week: " + dayOfWeek);

        // Display the specific date
        System.out.println("\nSpecific date: " + specificDate);
        System.out.println("Day of week for specific date: " + specificDate.getDayOfWeek());
    }
}

Compile and run the updated program:

javac DateComponents.java
java DateComponents

The output will now include information about the specific date:

Current date: 2023-04-12
Day of month: 12
Month (number): 4
Month (name): APRIL
Year: 2023
Day of week: WEDNESDAY

Specific date: 2025-12-25
Day of week for specific date: THURSDAY

You have now learned how to extract components from a LocalDate object and create dates for specific days. These capabilities are especially useful when building applications that need to perform date-based operations or display date information in different formats.

Summary

In this tutorial, you have learned how to work with dates in Java using the LocalDate class from the Java Time API. Here is a summary of what you accomplished:

  1. Created a Java program to retrieve the current date using LocalDate.now()
  2. Calculated future dates by adding days, weeks, months, and years to a date
  3. Extracted components from a date, such as day, month, year, and day of the week
  4. Created a specific date using the LocalDate.of() method

These basic date operations form the foundation for more complex date-based functionalities in Java applications. The Java Time API provides a comprehensive set of classes and methods for working with dates and times, making it easier to handle date-related requirements in your applications.

Some common applications of the knowledge you gained include:

  • Calculating due dates for tasks or payments
  • Scheduling events and appointments
  • Determining the day of the week for a specific date
  • Tracking time periods between events
  • Formatting dates for display in user interfaces

As you continue your Java journey, you can explore more advanced features of the Java Time API, such as working with time zones, formatting dates for different regions, and performing complex date calculations.