Java Date and Time Class
Common date-time APIs in Java can be divided into two categories:
- Old API versions:
Date,Calendar,SimpleDateFormat. - New Java 8 APIs:
LocalDate,LocalDateTime,Instant,DateTimeFormatter, etc.
Older versions of APIs are still encountered when maintaining historical code, but new projects usually use the java.time package first.
1. Timestamp and time zone
Unix timestamps usually represent the elapsed time since 1970-01-01T00:00:00Z. Date uses millisecond accuracy to store time points.
Beijing time usually uses 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 Category
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.
Many methods in Date that directly operate the year, month, and date calculation should use Calendar or the 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);
The value of long passed in 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 time point represented by this object.
Date is a mutable object, and calling setTime() will change the original object.
3. Calendar Category
Calendar 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 gets the instance through getInstance():
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.MONTHstarts from0, so1usually needs to be added when displaying the month.- The parameters of
add()can be positive or negative and can be used to increase or decrease the time. Calendaris also a mutable object.
Conversion with Date
Calendar calendar = Calendar.getInstance();
Date dateFromCalendar = calendar.getTime();
Date date = new Date(100_000_000L);
Calendar anotherCalendar = Calendar.getInstance();
anotherCalendar.setTime(date);
calendar.getTime(): Convert the time currently represented byCalendartoDate.calendar.setTime(date): LetCalendaruse the specified time point ofDate.
4. SimpleDateFormat Category
SimpleDateFormat is used to format and parse between Date and strings.
Common format symbols are as follows:
| symbol | meaning | example |
|---|---|---|
yyyy | Four-digit Year | 2026 |
MM | Two-month | 01 |
dd | Two digits date | 25 |
HH | 24-hour hour | 16 |
mm | minutes | 30 |
ss | seconds | 45 |
Format symbols are case sensitive. For example, MM represents the month and mm represents the minute.
Format Date 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);
}
}Parse 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) is used to turn off loose parsing. For example, in strict mode, 2026-02-30 will fail parsing instead of automatically adjusting to the next month.
SimpleDateFormat is not thread-safe, and the same instance should not be used as a shared object for multiple threads to use at the same time.
5. Old API applications
Add 15 days to the specified date
Add 15 days to 20260122 and output it 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 LocalDate and ChronoUnit.DAYS.
6. Java 8 Date and Time API
The type design of the java.time API 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 a course 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
| Type | Application Scenarios |
|---|---|
LocalDate | only requires the month, month, year, and time zone |
LocalTime | Only takes hours, seconds, seconds, and seconds |
LocalDateTime | requires date and time, but does not include time zone |
Instant | Time point on the Timeline, suitable for recording the timestamp |
ZonedDateTime | Date and time that requires clear time zone rules |
Duration | represents duration based on seconds and nanoseconds |
Period | represents the date difference based on year, month and day |
DateTimeFormatter | Format and interpretation of date and time |
New codes should be typed based on business meaning, rather than being saved using Date or strings at all times.
If you enjoyed this, leave a comment~