1.将LocalDateTime转为自定义的时间格式的字符串
public static String getDateTimeAsString(LocalDateTime localDateTime, String format) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
return localDateTime.format(formatter);
}
2.将long类型的timestamp转为LocalDateTime
public static LocalDateTime getDateTimeOfTimestamp(long timestamp) {
Instant instant = Instant.ofEpochMilli(timestamp);
ZoneId zone = ZoneId.systemDefault();
return LocalDateTime.ofInstant(instant, zone);
}
3.将LocalDateTime转为long类型的timestamp
public static long getTimestampOfDateTime(LocalDateTime localDateTime) {
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zone).toInstant();
return instant.toEpochMilli();
}
4.将某时间字符串转为自定义时间格式的LocalDateTime
public static LocalDateTime parseStringToDateTime(String time, String format) {
DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
return LocalDateTime.parse(time, df);
}
5.附一个获取当日凌晨时间戳的方式
@Test
public void testSystem(){
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
long timeInMillis = c.getTimeInMillis();
Instant instant = Instant.ofEpochMilli(timeInMillis);
ZoneId zone = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String format = format.format( localDateTime);
System.out.println(format);
}
最后看懂这个代码, 就提升了
long now = System.currentTimeMillis() / 1000l;
long daySecond = 60 * 60 * 24;
long dayTime = now - (now + 8 * 3600) % daySecond;
long nowTime =System.currentTimeMillis();
long todayStartTime =nowTime - ((nowTime + TimeZone.getDefault().getRawOffset()) % (24 * 60 * 60 * 1000L));