一、DateTime類與Date類的概述
Java中的DateTime類和Date類都是用來表示日期和時間的類,但是它們之間有很大的不同。
DateTime類是Java8中新增的一個時間日期API,它是線程安全的,同時提供了許多處理日期和時間的方法。Date類,是Java早期版本中就有的,但是它不是線程安全的,並且大多數方法已經被廢棄了,因此在實際項目中不建議使用。
二、DateTime轉Date的方法
在Java中,將DateTime對象轉換為Date對象的方法有很多,下面介紹幾種比較常用的方法。
1、使用toInstant()方法
DateTime類中提供了toInstant()方法,可以將當前的DateTime對象轉換為Instant對象,再通過Date.from()方法轉換為Date對象。
// 獲取當前時間
LocalDateTime now = LocalDateTime.now();
// 將當前時間轉換為 Instant 對象
Instant instant = now.toInstant(ZoneOffset.of("+8"));
// 轉換為 Date 對象
Date date = Date.from(instant);
System.out.println(date);
2、使用atZone()方法
DateTime類中提供了atZone()方法,可以將當前的DateTime對象轉換為ZoneDateTime對象,再通過toInstant()方法轉換為Instant對象,最後通過Date.from()方法轉換為Date對象。
// 獲取當前時間
LocalDateTime now = LocalDateTime.now();
// 轉換為帶時區的時間
ZonedDateTime zonedDateTime = now.atZone(ZoneId.systemDefault());
// 轉換為 Instant 對象
Instant instant = zonedDateTime.toInstant();
// 轉換為 Date 對象
Date date = Date.from(instant);
System.out.println(date);
3、使用Calendar類
另外一種方法是使用Calendar類,可將DateTime對象先轉換為LocalDateTime對象,再逐個獲取年月日時分秒,最後使用Calendar來設置時間。
// 獲取當前時間
LocalDateTime now = LocalDateTime.now();
// 轉換為LocalDateTime對象
LocalDateTime localDateTime = LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(), now.getHour(), now.getMinute(), now.getSecond());
// 使用Calendar類
Calendar calendar = Calendar.getInstance();
calendar.set(localDateTime.getYear(), localDateTime.getMonthValue()-1, localDateTime.getDayOfMonth(), localDateTime.getHour(), localDateTime.getMinute(), localDateTime.getSecond());
Date date = calendar.getTime();
System.out.println(date);
三、DateTime與Date的轉換小結
以上介紹了Java中將DateTime對象轉換為Date對象的三種方法:使用toInstant()方法、使用atZone()方法和使用Calendar類。
相比起來,toInstant()方法和atZone()方法更加直觀,而且日期的轉換明確,不容易出錯。而使用Calendar類的方法則比較繁瑣,需要逐個獲取年月日時分秒,但是在某些特殊場合,例如需要設置毫秒數的時候,則可以按照此方式進行處理。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/151853.html