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、DateTimeFormatterWait.
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.MONTHfrom0Start, so you usually need to add the month when displaying the month1。add()The parameter of can be positive or negative and can be used to increase or decrease the time.CalendarIt 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(): WillCalendarThe time currently represented is converted toDate。calendar.setTime(date): LetCalendarusing the specifiedDatethe time point.
4.SimpleDateFormat class
SimpleDateFormat for Date Format and parse between and string.
Common format symbols are as follows:
| symbol | meaning | example |
|---|---|---|
yyyy | Four years | 2026 |
MM | two-month | 01 |
dd | Two dates | 25 |
HH | 24 hourly hour | 16 |
mm | minutes | 30 |
ss | seconds | 45 |
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
| type | applicable scenarios |
|---|---|
LocalDate | Only the year, month, and time zone are needed |
LocalTime | It only takes minutes and seconds |
LocalDateTime | Date and time are required, but time zone is not included |
Instant | The time point on the Timeline, suitable for recording timestamps |
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 | Formatting 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.
If you enjoyed this, leave a comment~