I. Introduction
It is essential for everyone to deal with the date in the development process. When connecting to other systems, the format of the time and date is inconsistent, and it must be converted every time!
Every time I finish writing, I forget it. The editor specially organizes an article to explain in detail the conversion methods of the four of them, which is convenient for later use! !
Two, LocalDateTime, LocalDate, Date three contact
Let me talk about it here first, why is the date Date
already available , and it is still JDK8
launched in China LocalDateTime、LocalDate
?
Reason Date:
-
non-thread-safe method
Most of the methods of the Date class are not thread-safe, such as
setYear()、setMonth()、setDate()、setHours()、setMinutes()、setSeconds()
the etc. method. These methods can modify the internal state of the Date object. If an object多个线程
is accessed and modified at the same time同一个Date
, a race condition can occur, causing the program to behave incorrectly. -
Use of global variables
The Date class has two static variables, namely
DateParser
andCalendarSystem
. These two variables are全局共享
yes, and if multiple threads access and modify these two variables at the same time, it will also cause a race condition in the program.
Therefore, if you need to use date-time-related operations in threads, it is recommended to use thread-safe date-time classes, such as those in the new date-time API introduced in JDK8, or use thread-safe LocalDateTime、LocalDate
classes DateFormat和Calendar
.
Let's talk about how LocalDateTime achieves thread safety:
LocalDateTime is composed of two immutable classes, LocalDate and LocalTime. Both LocalDate and LocalTime are thread-safe, and their time information is UTC
calculated based on (coordinated universal time) and does not depend on the system's time zone settings. The same is true for LocalDateTime, which is calculated from the system time zone and UTC.
Those who are interested can take a look at: Introduction to Coordinated Universal Time
These classes mainly use the following two technologies to solve thread safety issues:
-
Immutability: These classes are immutable, once created, they cannot be modified. Therefore, there is no problem of concurrent modification.
-
Thread closure: The constructors of these classes are thread-safe and do not allow external modification of the state. Therefore, there is no need to protect their state through locks or other mechanisms.
To sum up, the new date and time API in Java 8 effectively solves the problem of thread safety through technologies such as and 不可变性
. 线程封闭性
This allows developers to use date and time classes in a multi-threaded environment more safely and conveniently.
Basically, the new system will use LocalDateTime as the date and time to reduce concurrency problems!
Three, mutual conversion example
1. LocalDate to String
The LocalDate class has a format() method that converts a date into a string. The format() method takes a DateTimeFormatter object as a parameter. In the following code example, we convert a date object to a string.
String dateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
System.out.println("当前字符串日期:" + dateStr);
2. String to LocalDate
We can parse date object from string using parse() method
LocalDate date = LocalDate.parse(dateStr);
System.out.println("日期对象:" + date);
3. LocalDateTime to String
Similarly, we can use the DateTimeFormatter class to format a date object of type LocalDateTime into a string.
String dateTimeStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println("当前字符串日期时间:" + dateTimeStr);
4. String to LocalDateTime
We can also parse datetime objects from strings using the parse() method.
LocalDateTime dateTime = LocalDateTime.parse(dateTimeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println("当前日期时间对象:" + dateTime);
Since versions before Java 8 use the Date class to handle date and time, it is very common to convert Java 8 date and time to the Date type, and we can use the following methods to operate.
5. LocalDate转Date
Date dateNew1 = Date.from(date.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
System.out.println("当前日期对象转date:" + dateNew1);
6. LocalDateTime to Date
Date dateNew2 = Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());
System.out.println("当前日期时间对象转date:" + dateNew2);
7. Date转LocalDate
LocalDate localDate = dateNew2.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println("当前date转日期对象:" + localDate);
8. Date to LocalDateTime
LocalDateTime localDateTime = dateNew2.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
System.out.println("当前date转日期时间对象:" + localDateTime);
9. Date to String
You can extract a method by yourself and convert it into the format you want according to the format! You can also use third-party format conversion, such as:hutool
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("date转String字符串:" + df.format(dateNew2));
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("String字符串转date:" + df1.parse(dateTimeStr));
have to be aware of is
SimpleDateFormat
It is a thread-unsafe class and is not suitable for multi-threaded environments, so you need to pay attention to thread safety issues in actual development. Can be considered ThreadLocal
to solve thread safety problems.
public class ThreadSafeDateFormat {
private ThreadLocal<DateFormat> dateFormatThreadLocal = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
public DateFormat get() {
return dateFormatThreadLocal.get();
}
}
ThreadSafeDateFormat dateFormat = new ThreadSafeDateFormat();
System.out.println("date转String字符串安全版:" + dateFormat.get().format(dateNew2));
System.out.println("String字符串转date安全版:" + dateFormat.get().parse(dateTimeStr));
Four. Summary
It should be noted that you need to pay attention to the time zone and timestamp when using it, otherwise some errors may occur.
In short, mastering the conversion methods between these types can improve our development efficiency, avoid some common mistakes, and handle date and time related tasks more efficiently in actual development.
If it is helpful to you, please move your little hands of making money and pay attention to the official account! ! thanks for your attention! !