Java Date and Time Class

Published 2026-07-30 20:20 Updated 2026-10-13 17:14 1088 words 6 min read ... Page views AI-reviewed An AI proof-read this post, but it still deserves a careful read. AI-rewritten Someone else wrote the original; AI helped me rewrite and polish it.

AI-reviewed An AI proof-read this post, but it still deserves a careful read.

This article introduces date-time related APIs in Java, which are divided into two categories: old versions (Date, Calendar, SimpleDateFormat) and new versions (java.time package). Although the old version of the API can still be used for historical code maintenance, it has problems such as variability, thread insecurity and error-prone. It is recommended to use the immutable and thread-safe java.time API for new projects. The new Java 8 API provides clearer and more secure date-time classes, such as LocalDate, LocalDateTime, and DateTimeFormatter, which support precise date calculation and formatting and are recommended to be used first in new projects.

Java Date and Time Class

Common date-time APIs in Java can be divided into two categories:

  • Old API:Date、Calendar、SimpleDateFormat。
  • New Java 8 APIs:LocalDate、LocalDateTime、Instant、DateTimeFormatter Wait.

Older versions of APIs are still encountered when maintaining historical code, but new projects are usually preferred java.time bag.

1. Timestamp and time zone

Unix timestamps usually represent data from 1970-01-01T00:00:00Z The time that began to pass.Date Save points in time with millisecond precision.

Beijing time is usually used UTC+8。The time zone affects how the time point is displayed as year, year, and hour, minute and second, but does not change the time point itself.

2.Date class

java.util.Date Represents a point in time on the Timeline, and the internal core value is the number of milliseconds calculated since the Unix era. It does not simply save the year, month, day, hour, minute, and second separately.

Date Many methods of directly operating the year, month, and date calculation should be used Calendar or more recommended java.time API。

constructor

Date now = new Date();

A parameterless constructor creates an object that represents the current time.

Date date = new Date(1_000_000L);

incoming long Value represents the number of milliseconds that have passed since the beginning of the Unix era.

common methods

Date date = new Date();

long timestamp = date.getTime();
date.setTime(timestamp + 1_000L);
  • getTime(): Get the millisecond timestamp.
  • setTime(long time): Modify the point in time represented by this object.

Date Is a mutable object, calling setTime() Will change the original object.

3.Calendar class

Calendar It is an old calendar calculation class that can process fields such as year, month, and month based on time zone and regional settings.

Its constructor is usually not called directly, but is called via getInstance() Get examples:

Calendar calendar = Calendar.getInstance();

Get and modify date fields

Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, 3);

int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);

System.out.println(year + "-" + month + "-" + day);

Note:

  • Calendar.MONTH from 0 Start, so you usually need to add the month when displaying the month 1。
  • add() The parameter of can be positive or negative and can be used to increase or decrease the time.
  • Calendar It is also a mutable object.

with Date mutual conversion

Calendar calendar = Calendar.getInstance();
Date dateFromCalendar = calendar.getTime();

Date date = new Date(100_000_000L);
Calendar anotherCalendar = Calendar.getInstance();
anotherCalendar.setTime(date);
  • calendar.getTime(): Will Calendar The time currently represented is converted to Date。
  • calendar.setTime(date): Let Calendar using the specified Date the time point.

4.SimpleDateFormat class

SimpleDateFormat for Date Format and parse between and string.

Common format symbols are as follows:

symbolmeaningexample
yyyyFour years2026
MMtwo-month01
ddTwo dates25
HH24 hourly hour16
mmminutes30
ssseconds45

Format symbols are case sensitive. example,MM Represents the month,mm Represents minutes.

will Date Format as a string

import java.text.SimpleDateFormat;
import java.util.Date;

public class FormatDateDemo {

    public static void main(String[] args) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();

        String text = formatter.format(now);
        System.out.println(text);
    }
}

Parses a string to Date

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ParseDateDemo {

    public static void main(String[] args) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        formatter.setLenient(false);

        String text = "2026-01-25";

        try {
            Date date = formatter.parse(text);
            System.out.println(date);
        } catch (ParseException e) {
            System.out.println("日期格式不正确");
        }
    }
}

setLenient(false) Used to turn off loose parsing. For example, in strict mode,2026-02-30 The resolution will fail instead of automatically adjusting to the next month.

SimpleDateFormat It is not thread-safe and should not use the same instance as a shared object for multiple threads to use simultaneously.

5. Old API applications

Add 15 days to the specified date

will 20260122 Add 15 days and output them in Chinese date format:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class AddDaysLegacyDemo {

    public static void main(String[] args) {
        String text = "20260122";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        formatter.setLenient(false);

        try {
            Date date = formatter.parse(text);

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.DATE, 15);

            formatter.applyPattern("yyyy年MM月dd日");
            System.out.println(formatter.format(calendar.getTime()));
        } catch (ParseException e) {
            System.out.println("日期格式不正确");
        }
    }
}

Calculate the millisecond difference between two time points

long differenceMillis = endDate.getTime() - startDate.getTime();

Divide directly by the number of milliseconds in a day only yields the number of days in the sense of a fixed duration. If the time range changes across daylight saving time, the results may differ from the calendar date. Therefore, when calculating the number of days difference between dates, it is more suitable to use the LocalDate and ChronoUnit.DAYS。

6. Java 8 Date and Time API

java.time The API’s type design is clearer, and most core classes are immutable and thread-safe.

LocalDate

LocalDate Represents a date without a time zone, such as a birthday or class date.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class LocalDateDemo {

    public static void main(String[] args) {
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");

        LocalDate date = LocalDate.parse("20260122", inputFormatter);
        LocalDate result = date.plusDays(15);

        System.out.println(result.format(outputFormatter));
    }
}

Calculate date difference

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class DateDifferenceDemo {

    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");

        LocalDate startDate = LocalDate.parse("20260122", formatter);
        LocalDate endDate = LocalDate.parse("20260302", formatter);

        long days = ChronoUnit.DAYS.between(startDate, endDate);
        System.out.println(days);
    }
}

common types

typeapplicable scenarios
LocalDateOnly the year, month, and time zone are needed
LocalTimeIt only takes minutes and seconds
LocalDateTimeDate and time are required, but time zone is not included
InstantThe time point on the Timeline, suitable for recording timestamps
ZonedDateTimeDate and time that requires clear time zone rules
DurationRepresents duration based on seconds and nanoseconds
PeriodRepresents the date difference based on year, month, and day
DateTimeFormatterFormatting and parsing of date and time

New code should be typed based on business meaning, rather than being used all the time Date or string save.

Written by AI-rewritten

If you enjoyed this, leave a comment~

Loading...