Summary of related usage of Java date and time API
- 2021-08-21 20:18:07
- OfStack
2. JDK Native API
1. Date Foundation
2. Calendar upgrade
3. JDK1.8 Upgrade API
4. Timestamp
3. JodaTime component
4. Source code address
1. Time and date
In the system development, date and time, as important business factors, play a key role in 10 points, such as data generation under the same time node, statistics and analysis of various data based on time range, and avoiding timeout in cluster nodes.
There are several key concepts in time and date:
Date: Usually the combination of year, month and day represents the current date. Time: Usually, the combination of minutes and seconds represents the current time. Time zone: Different countries and regions in the world have different longitudes, which are divided into 24 standard time zones, and the time difference between adjacent time zones is 1 hour. Timestamp: The total number of seconds from 1970-1-1 00:00:00 UTC to the present.The usage of date and time in the system is usually to obtain time and some common calculation and format conversion processing, which will become much more complicated in some businesses that break the time zone, such as global trade or Haitao in e-commerce business.
2. JDK Native API
1. Date Foundation
Basic usage
java. sql. Date inherits java. util. Date, and most of the related methods directly call the parent class methods.
public class DateTime01 {
public static void main(String[] args) {
long nowTime = System.currentTimeMillis() ;
java.util.Date data01 = new java.util.Date(nowTime);
java.sql.Date date02 = new java.sql.Date(nowTime);
System.out.println(data01);
System.out.println(date02.getTime());
}
}
Print:
Fri Jan 29 15:11:25 CST 2021
1611904285848
Calculation rule
public class DateTime02 {
public static void main(String[] args) {
Date nowDate = new Date();
System.out.println(" Year :"+nowDate.getYear());
System.out.println(" Month :"+nowDate.getMonth());
System.out.println(" Day :"+nowDate.getDay());
}
}
Year: Current time minus 1900;
public int getYear() {
return normalize().getYear() - 1900;
}
Month: 0-11 means January-December;
public int getMonth() {
return normalize().getMonth() - 1;
}
Talent: Normal expression;
public int getDay() {
return normalize().getDayOfWeek() - BaseCalendar.SUNDAY;
}
Format conversion
Non-thread-safe date conversion API, which is not allowed in the development of the specification.
public class DateTime02 {
public static void main(String[] args) throws Exception {
// Default conversion
DateFormat dateFormat01 = new SimpleDateFormat() ;
String nowDate01 = dateFormat01.format(new Date()) ;
System.out.println("nowDate01="+nowDate01);
// Specify format conversion
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat dateFormat02 = new SimpleDateFormat(format);
String nowDate02 = dateFormat02.format(new Date()) ;
System.out.println("nowDate02="+nowDate02);
// Parsing time
String parse = "yyyy-MM-dd HH:mm";
SimpleDateFormat dateFormat03 = new SimpleDateFormat(parse);
Date parseDate = dateFormat03.parse("2021-01-18 16:59:59") ;
System.out.println("parseDate="+parseDate);
}
}
As the date and time used in the initial version of JDK, Date Class 1 is directly used in the project, but the methods related to API have been basically discarded, and 1 or 2 encapsulated time components are usually used. The design of this API is the worst among Java.
2. Calendar upgrade
Calendar, as an abstract class, defines the methods of date-time related transformation and calculation
public class DateTime04 {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,2021);
calendar.set(Calendar.MONTH,1);
calendar.set(Calendar.DAY_OF_MONTH,12);
calendar.set(Calendar.HOUR_OF_DAY,23);
calendar.set(Calendar.MINUTE,59);
calendar.set(Calendar.SECOND,59);
calendar.set(Calendar.MILLISECOND,0);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
Date defDate = calendar.getTime();
System.out.println(defDate+"||"+dateFormat.format(defDate));
}
}
Output: Fri Feb 12 23:59:59 CST 2021||2021-02-12 23:59:59
Intuitively, the related methods in Date migrate the implementation of Calendar, simplify the functions of Date, focus on the physical encapsulation of date and time, Calendar complex related calculation strategies, and DateFormat is still used for format processing. However, Calendar is still rarely used, and the above basic API is already a good illustration.
3. JDK1.8 upgrades API
In versions after Java8, the core API class includes LocalDate-date, LocalTime-time, and LocalDateTime-date plus time.
LocalDate: Date descriptions are immutable classes of final modifications, and the default format is yyyy-MM-dd. LocalTime: Time descriptions are immutable classes of final modifications, and the default format is hh: mm: ss. zzz. LocalDateTime: Date and time descriptions are immutable classes of final modifications.
public class DateTime05 {
public static void main(String[] args) {
// Date: Year - Month - Day
System.out.println(LocalDate.now());
// Time: Hour - Points - Seconds - Milliseconds
System.out.println(LocalTime.now());
// Date and time: Year - Month - Day Hour - Points - Seconds - Milliseconds
System.out.println(LocalDateTime.now());
// Date node acquisition
LocalDate localDate = LocalDate.now();
System.out.println("[" + localDate.getYear() +
" Year ] ; [" + localDate.getMonthValue() +
" Month ] ; [" + localDate.getDayOfMonth()+" Day ]");
// Calculation method
System.out.println("1 Years later: " + localDate.plusYears(1));
System.out.println("2 Months ago: " + localDate.minusMonths(2));
System.out.println("3 After weeks: " + localDate.plusWeeks(3));
System.out.println("3 Days ago: " + localDate.minusDays(3));
// Time comparison
LocalTime localTime1 = LocalTime.of(12, 45, 45); ;
LocalTime localTime2 = LocalTime.of(16, 30, 30); ;
System.out.println(localTime1.isAfter(localTime2));
System.out.println(localTime2.isAfter(localTime1));
System.out.println(localTime2.equals(localTime1));
// Date and time format
LocalDateTime localDateTime = LocalDateTime.now() ;
LocalDate myLocalDate = localDateTime.toLocalDate();
LocalTime myLocalTime = localDateTime.toLocalTime();
System.out.println(" Date: " + myLocalDate);
System.out.println(" Time: " + myLocalTime);
}
}
If you are a deep user of JodaTime components, there is basically no pressure to use these several API.
4. Timestamp
Time stamp is also a common way in business. It is based on Long type to represent time, which is far better than the conventional date and time format in many cases.
public class DateTime06 {
public static void main(String[] args) {
// Accurate to millisecond level
System.out.println(System.currentTimeMillis());
System.out.println(new Date().getTime());
System.out.println(Calendar.getInstance().getTime().getTime());
System.out.println(LocalDateTime.now().toInstant(
ZoneOffset.of("+8")).toEpochMilli());
}
}
It should be noted here that in actual business, because there are various ways to obtain timestamps, it is suggested to unify the tools and methods, and specify the accuracy to avoid the problem of partial accuracy to seconds and partial accuracy to milliseconds, so as to avoid the situation of mutual conversion when using them.
3. JodaTime Components
Prior to Java8, the JodaTime component was a common choice in most systems, and there are many convenient and easy-to-use date and time processing methods encapsulated.
Base dependencies:
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
joda-time provides a simple tool class package on the components to ensure business processing style 1.
public class DateTime02 {
public static void main(String[] args) {
Date nowDate = new Date();
System.out.println(" Year :"+nowDate.getYear());
System.out.println(" Month :"+nowDate.getMonth());
System.out.println(" Day :"+nowDate.getDay());
}
}
0
4. Source code address
GitHub · Address
https://github.com/cicadasmile/java-base-parent
GitEE · Address
https://gitee.com/cicadasmile/java-base-parent
The above is the Java date and time API related usage summary of the details, more information about Java date and time api please pay attention to other related articles on this site!