jdk8中新加入的日期类,大大方便了我们对日期的操作,可有时也会因为对某些类的不熟悉,导致迟迟找不到解决
办法,下面我就对自己所使用的一些方法做一些记录,方便以后查阅。
1.日期
LocalDate localDate = LocalDate.now()
System.out.println(localDate.toString())
System.out.println(localDate.plusDays(1))
System.out.println(localDate.minusDays(1))
System.out.println(localDate.atStartOfDay())
System.out.println(localDate.atStartOfDay().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
System.out.println(localDate.plusDays(1).atStartOfDay().minusSeconds(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
System.out.println(localDate.atTime(23,59,59).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
System.out.println(localDate.lengthOfYear())
System.out.println(localDate.getDayOfYear())
System.out.println(localDate.getDayOfWeek().getValue())
System.out.println(localDate.getMonth().getValue())
System.out.println(localDate.getMonthValue())
// 2.时间
LocalDateTime localDateTime = LocalDateTime.now()
System.out.println(localDateTime)
System.out.println(localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
System.out.println(localDateTime.atZone(ZoneId.of(ZoneId.SHORT_IDS.get("CTT"))).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) )
// 3.与Date转换
LocalDateTime localDateTime1 = LocalDateTime.now()
Instant instant = localDateTime1.atZone(ZoneId.of("Asia/Shanghai")).toInstant()
Date date = Date.from(instant)
// 获取时间戳
long timestamp = date.getTime()
System.out.println(timestamp)
Instant instant1 = Instant.ofEpochMilli(timestamp)
System.out.println(instant1.atZone(ZoneId.of("Asia/Shanghai")).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))