簡述
Java 8 中 日期,時間API 完全重構。拋棄了原來非常複雜的 calendar. 還加入了線程安全的等更加友好的API。本文主要是記錄分享 常用的 時間所在周,月,季度,年的 第一天獲取方式。
週一
/**
* 獲取時間戳的第一週
* @param timestamp long
* @return long
*/
public static long getWeek1st(long timestamp) {
return Instant.ofEpochMilli(timestamp).atZone(ZoneId.systemDefault()).with(DayOfWeek.MONDAY)
.toInstant().toEpochMilli();
}
月第一天
/**
* 獲取時間戳的月第一天
* @param timestamp 時間戳
* @return long
*/
public static long getMonth1st(long timestamp) {
return Instant.ofEpochMilli(timestamp).atZone(ZoneId.systemDefault())
.with(TemporalAdjusters.firstDayOfMonth()).toInstant().toEpochMilli();
}
季度第一天
/**
* 獲取季度的一天
* @param timestamp
* @return
*/
public static long quarterStart(long timestamp) {
int month = Instant.ofEpochMilli(timestamp).atZone(ZoneId.systemDefault()).getMonth().getValue();
final LocalDate date = Instant.ofEpochMilli(timestamp).atZone(ZoneId.systemDefault()).toLocalDate();
int start = 0;
// 第一季度
if (month <= 3) {
start = 1;
} else if (month <= 6) {
start = 4;
} else if (month <= 9) {
start = 7;
} else {
start = 10;
}
return date.plusMonths(start - month).with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay()
.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
}
當前年第一天
/**
* 當前年的第1天
* @return
*/
public static long getCurrentYear1st() {
return LocalDate.now().atStartOfDay().with(TemporalAdjusters.firstDayOfYear()).atZone(ZoneId.systemDefault())
.toInstant().toEpochMilli();
}
總結
本文主要涉及的重點
時間戳轉換爲LocalDate,需要設置時區。
Instant.ofEpochMilli(timestamp).atZone(ZoneId.systemDefault())
LocalDate 獲取 周,月,年的第一天使用with
TemporalAdjusters.firstDayOfYear()
DayOfWeek.MONDAY
TemporalAdjusters.firstDayOfMonth()
沒有直接提供季度的方式,需要計算
如果文章有些許幫助,請關注,點贊吆。