preface
Assuming you want to get the current time, you’ve probably seen code like this
public static void main(String[] args) {
Date date = new Date(System.currentTimeMillis());
System.out.println(date.getYear());
System.out.println(date.getMonth());
System.out.println(date.getDate());
}
Copy the code
Get year, get month, get.. The date? Run the
September 27 121Copy the code
What’s going on? Get year, date how all wrong, open source to find
/** * Returns a value that is the result of subtracting 1900 from the * year that contains or begins with the instant in time represented * by this <code>Date</code> object, as interpreted in the local * time zone. * * @return the year represented by this date, Minus 1900. * @see java.util.Calendar * @deprecated As of JDK version 1.1, * replaced by <code>Calendar.get(Calendar.YEAR) - 1900</code>. */ @Deprecated public int getYear() { return normalize().getYear() - 1900; }Copy the code
It turns out that 1900 is subtracted from some object value, and the comment also says that 1900 is subtracted from the return value. Do we need to add 1900 every time we get the year? The comment also says let’s use calendar.get () instead, and that method is deprecated. Clicking getMonth() does the same, returning a value from 0 to 11. GetDate () gets the date? Shouldn’t it be getDay()? GetDate () getDate() getDate() Note that these apis were deprecated in 1.1, presumably to eliminate ambiguity about getYear minus 1900. Close ~
Calendar Calendar class
public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int dom = calendar.get(Calendar.DAY_OF_MONTH); int doy = calendar.get(Calendar.DAY_OF_YEAR); int dow = calendar.get(Calendar.DAY_OF_WEEK); int dowim = calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH); System.out.println(year+" year "+ month+" month "); System. The out. Println (dom + ", "); System. The out. Println (doy + ", "); System. The out. Println (dow + ", "); System.out.println(dowim); }Copy the code
Print (Run time oct 27, 2021 Wednesday Fine)
September 27, 2021, 300 days, 4 days, 4 daysCopy the code
Q: how come the month is last month? A: For ease of calculation, the month is a value between 0 and 11. Q: Easy to calculate? A: For example, if the month starts from January and one month is added, December +1=13, there is no 13. If the mod, (12+1)%12=1 is exactly 1 month, then add one month in November, (11+1)%12=0, then there is a problem. So in order to calculate the month of 1, 0 is returned. Date.getmonth () is the same. Q: what does “DAY_OF_XXX” mean? A: guess! Guess from the result. DAY_OF_MONTH is on this day of the month.DAY_OF_YEAR is on this day of the year.DAY_OF_WEEK is on this day of the week DAY_OF_WEEK_IN_MONTH why is DAY_OF_WEEK 4? HOUR calendar. HOUR_OF_DAY calendar. SECOND… I’m sure you know how to use the rest
LocalDate LocalDate class
LocalDate localDate = LocalDate.now(); System.out.println(" current date: "+localDate.getMonthValue()+" localDate.getMonthValue() "+ "localDate.getDayOfMonth()"); // Results Current date: October 27, 2021Copy the code
Localdate. of(year, month, day) is also available
LocalDate pluslocalDate = localDate.plusDays(1); PluslocalDate = localdate.plusyears (1); // Add a yearCopy the code
Other apis
LocalDate.isBefore(LocalDate);
LocalDate.isAfter();
LocalDate.isEqual();
Copy the code
That is, two dates are judged to be before, after, or equal.
LocalTime LocalTime class
LocalTime localTime = LocalTime.now(); System.out.println(" current time: "+ localtime.gethour ()+"h "+ localtime.getSecond ()+"m "+ localtime.getminute ()+"s");Copy the code
Localdate.plusdays (1) increment localtime.plushours (1) increment localtime.plushours (1) increment localtime.plushours (1) increment localtime.plushours (1) increment localtime.plushours (1) increment localtime.plushours (1) increment localtime.plushours (1) increment localtime.plushours
LocalTime.isBefore(LocalTime);
LocalTime.isAfter();
Copy the code
The judgment of two times. There must have been a need to know how many days are left until the event starts today.
LocalDateTime LocalDateTime class
public final class LocalDateTime ... { private final LocalDate date; private final LocalTime time; }Copy the code
LocalDateTime = LocalDate + LocalTime
Instant class
An Instant is an Instant
Instant.ofEpochMilli(System.currentTimeMillis())
Instant.now()
Copy the code
Instant allows you to create a “moment” object, and ofEpochMilli() can accept a moment, such as the current time, or a time in the past or future. For example, create a LocalDateTime object from a “moment”
LocalDateTime now = LocalDateTime.ofInstant( Instant.ofEpochMilli(System.currentTimeMillis()),ZoneId.systemDefault()); System.out.println(" current date: "+now.getMonthValue()+" now.getMonthValue() "+ "now.getMonthValue() "+" now.getDayOfMonth() ");Copy the code
Period which
Period there’s a between method that compares two dates
LocalDate startDate = LocalDateTime.ofInstant( Instant.ofEpochMilli(1601175465000L), ZoneId.systemDefault()).toLocalDate(); Period p = Period. Between (startDate, localdate.now ()); System.out.println(" time difference between target date and today: "+ p.gettyears ()+ p.gettmonths ()+ p.gettdays ()+" days "); // Target date: 1 year, 1 month, 1 dayCopy the code
Take a look at the source code
public static Period between(LocalDate startDateInclusive, LocalDate endDateExclusive) {
return startDateInclusive.until(endDateExclusive);
}
public Period until(ChronoLocalDate endDateExclusive) {
LocalDate end = LocalDate.from(endDateExclusive);
long totalMonths = end.getProlepticMonth() - this.getProlepticMonth(); // safe
int days = end.day - this.day;
if (totalMonths > 0 && days < 0) {
totalMonths--;
LocalDate calcDate = this.plusMonths(totalMonths);
days = (int) (end.toEpochDay() - calcDate.toEpochDay()); // safe
} else if (totalMonths < 0 && days > 0) {
totalMonths++;
days -= end.lengthOfMonth();
}
long years = totalMonths / 12; // safe
int months = (int) (totalMonths % 12); // safe
return Period.of(Math.toIntExact(years), months, days);
}
Copy the code
It takes only two LocalDate objects, calculates the time, and returns a Period object
Duration class
Duration is a code for the Duration of a period
LocalDateTime end = LocalDateTime.ofInstant(Instant.ofEpochMilli(System.currentTimeMillis()), ZoneId.systemDefault()); LocalDateTime start = LocalDateTime.ofInstant(Instant.ofEpochMilli(1601175465000L), ZoneId.systemDefault()); Duration duration = Duration.between(start, end); System.out.println(" start time to end time, duration "+ duration.todays ()+" days "); System.out.println(" start time to end time, duration "+ duration.tohours ()+" hours "); System.out.println(" start time to end time, duration "+ duration.tomillis ()/1000+" seconds ");Copy the code
As you can see, between also takes two arguments, a LocalDateTime object. The source code is a calculation of two times, and returns an object.
Object conversion
Put another API
//long -> LocalDateTime LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault()) //String -> LocalDateTime DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime.parse("2021-10-28 00:00:00", dateTimeFormatter1); AtZone (zoneid.systemDefault ()).toInstant().toepochmilli (); //LocalDateTime -> long LocalDateTime object. //LocalDateTime -> String DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime object. The format (dateTimeFormatter1)Copy the code
Object conversion is almost always covered, there is a time zone object, this is usually the default time zone.
conclusion
Date classes are replaced with LocalDate, LocalTime, and LocalDateTime. LocalDateTime = LocalDate + LocalTime Period LocalDate Duration So LocalDate, LocalTime, LocalDateTime can handle all of this and the Calendar class, the API in here, is all for calendars, like what day of the week is the first day of the month. Use localDate.getMonthValue() to get the number of months.