前言
在java开发中,不可避免的需要使用到时间(不论是时间戳还是日期等),在java8出来以后,相关的时间类就替代了曾经的,我们对应得的使用方法当然也随之改变。下面就给出例子介绍使用java8的 LocalDate 等相关方法获取时间并作出对应得处理。
相关工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| public static void localDateTime() { LocalDateTime localDateTime = LocalDateTime.now(); System.out.println(localDateTime); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); System.out.println(localDateTime.format(formatter)); } public static void localDate() { LocalDate localDate = LocalDate.now(); System.out.println(localDate); } public static void localTime() { LocalTime localTime = LocalTime.now(); System.out.println(localTime); } public static void dayZero() { Long nowTime = System.currentTimeMillis(); Long dayZero = nowTime - ((nowTime + TimeZone.getDefault().getRawOffset()) % (24 * 60 * 60 * 1000L)); System.out.println(dayZero); } public static void startDayTime() { LocalDate localDate = LocalDate.now(); LocalDate localDate1 = localDate.withDayOfMonth(1); long startDayTime = localDate1.atStartOfDay(ZoneOffset.ofHours(8)).toInstant().toEpochMilli(); System.out.println(startDayTime); } public static void lastDayTime() { LocalDate localDate = LocalDate.now(); LocalDate lastDay = localDate.with(TemporalAdjusters.lastDayOfMonth()); long lastDayTime = lastDay.atStartOfDay(ZoneOffset.ofHours(8)).toInstant().toEpochMilli() + (24 * 60 * 60 * 1000L - 1); System.out.println(lastDayTime); } public String getDayOfWeek() { LocalDate localDate = LocalDate.now(); return String.valueOf(localDate.getDayOfWeek().getValue()); } public String getDayOfWeek(Long timeZero) { LocalDate localDate = Instant.ofEpochMilli(timeZero).atZone(ZoneOffset.ofHours(8)).toLocalDate(); return String.valueOf(localDate.getDayOfWeek().getValue()); } public static void main(String[] args) { localDateTime(); localDate(); localTime(); dayZero(); startDayTime(); lastDayTime(); getDayOfWeek(); getDayOfWeek(1598352076000L); }
|
结语
当然,还有其他的相关还没写完,留在后续补充吧,感觉这些已经暂时够用了……