今天在使用LocalDateTime時需要將時間轉化使勁啊戳,原來我也沒怎麼用過.
發現又一個方法
default long toEpochSecond(ZoneOffset offset) {
Objects.requireNonNull(offset, "offset");
long epochDay = toLocalDate().toEpochDay();
long secs = epochDay * 86400 + toLocalTime().toSecondOfDay();
secs -= offset.getTotalSeconds();
return secs;
}
這個方法需要傳入一個ZoneOffset的對象,經過查詢資料是這麼做的
public static Long localDateTime2LongSecond(LocalDateTime localDateTime) {
//獲得當前時區
Instant instant = Instant.now();
ZoneId systemZone = ZoneId.systemDefault();
ZoneOffset currentOffsetForMyZone =
systemZone.getRules().getOffset(instant);
return localDateTime.toEpochSecond(currentOffsetForMyZone);
}
然而,我自己測試的時候發現該方法返回的時間戳和Date的時間戳有1000倍的出入
1570712734
1570712734225
發現LocalDateTime的toEpochSecond方法返回的單位是秒,而Date.getTime()返回的單位是毫秒.
源碼的註釋也有說明只是我給漏掉了,第一行就說了是seconds
/**
* Converts this date-time to the number of seconds from the epoch
* of 1970-01-01T00:00:00Z.
* <p>
* This combines this local date-time and the specified offset to calculate the
* epoch-second value, which is the number of elapsed seconds from 1970-01-01T00:00:00Z.
* Instants on the time-line after the epoch are positive, earlier are negative.
* <p>
* This default implementation calculates from the epoch-day of the date and the
* second-of-day of the time.
*
* @param offset the offset to use for the conversion, not null
* @return the number of seconds from the epoch of 1970-01-01T00:00:00Z
*/
default long toEpochSecond(ZoneOffset offset) {
Objects.requireNonNull(offset, "offset");
long epochDay = toLocalDate().toEpochDay();
long secs = epochDay * 86400 + toLocalTime().toSecondOfDay();
secs -= offset.getTotalSeconds();
return secs;
}
真正的實現方式是
/**
* @description: 有LocalDateTime轉換成時間戳(毫秒 )
* @param: [localDateTime]
* @return: java.lang.Long
* @author: lky
* @date: 2019/10/10 09:57
*/
public static Long localDateTime2Long(LocalDateTime localDateTime) {
//獲得當前時區
Instant instant = Instant.now();
ZoneId systemZone = ZoneId.systemDefault();
ZoneOffset currentOffsetForMyZone = systemZone.getRules().getOffset(instant);
return localDateTime.atZone(currentOffsetForMyZone).toInstant().toEpochMilli();
}
另送時間戳轉換爲LocalDateTime的方法,*1000的操作是爲了將(秒)轉換爲毫秒 ,請忽略
/**
* @description: 將Long類型的時間戳轉換爲LocalDateTime類型
* @param: [timestamp]
* @return: java.time.LocalDateTime
* @author: lky
* @date: 2019/10/9 11:08
*/
public static LocalDateTime getDateTimeOfTimestamp(long timestamp) {
if ((timestamp + "").length() < 13) {
timestamp *= 1000;
}
Instant instant = Instant.ofEpochMilli(timestamp);
ZoneId zone = ZoneId.systemDefault();
return LocalDateTime.ofInstant(instant, zone);
}