新日期和时间
程序员文章站
2022-05-31 10:06:26
...
@Test public void createDate() { LocalDateTime now = LocalDateTime.now(); System.out.println("当前日期和时间:"+now); LocalDateTime assignDateTime=LocalDateTime.of(2019,10,22, 17, 20, 20); System.out.println("指定日期和时间:"+assignDateTime); String date="2020-01-01T00:00:00.000"; LocalDateTime parse = LocalDateTime.parse(date); System.out.println("解析日期和时间"+parse); System.out.println("================="); LocalDate localDate = now.toLocalDate(); System.out.println("当前日期:"+localDate); LocalDate assignDate = LocalDate.of(2019, Month.NOVEMBER, 11); System.out.println("指定日期:"+assignDate); System.out.println("================="); LocalTime localTime = now.toLocalTime(); System.out.println("当前时间:"+localTime); } 输出: 当前日期和时间:2019-11-18T18:53:47.313 指定日期和时间:2019-10-22T17:20:20 解析日期和时间2020-01-01T00:00 ================= 当前日期:2019-11-18 指定日期:2019-11-11 ================= 当前时间:18:53:47.313 @Test public void getDate() { LocalDate now = LocalDate.now(); System.out.println("当前年:"+now.getYear()); System.out.println("当前月:"+now.getMonth().getValue()); System.out.println("当前周的第几天:"+now.getDayOfWeek().getValue()); System.out.println("当前月的第几天:"+now.getDayOfMonth()); System.out.println("当前年的第几天:"+now.getDayOfYear()); System.out.println("明天:"+now.plusDays(1)); } 输出: 当前年:2019 当前月:11 当前周的第几天:1 当前月的第几天:18 当前年的第几天:322 明天:2019-11-19 @Test public void getTime() { LocalTime now = LocalTime.now(); System.out.println("当前时间:"+now); System.out.println("当前时:"+now.getHour()); System.out.println("当前分:"+now.getMinute()); System.out.println("当前秒:"+now.getSecond()); System.out.println("当前毫秒:"+now.get(ChronoField.MILLI_OF_SECOND)); System.out.println("当前纳秒:"+now.getNano()); } 输出: 当前时间:18:56:53.925 当前时:18 当前分:56 当前秒:53 当前毫秒:925 当前纳秒:925000000 @Test public void parseDate(){ //字符串转时间 DateTimeFormatter formatter =DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String date="2019-11-28 11:28:15"; LocalDateTime parse = LocalDateTime.parse(date, formatter); System.out.println("字符串转时间:"+parse); //时间转字符串 String format = LocalDateTime.now().format(formatter); System.out.println("时间转字符串:"+format); System.out.println("================="); //获取从1970-01-01 00:00:00到现在的秒数或毫秒数,由于中国时间比欧洲早8小时所以ZoneOffset.of("+8") long epochSecond = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")); System.out.println("从1970-01-01到现在的总秒数:"+epochSecond); Instant instant = LocalDateTime.now().toInstant(ZoneOffset.of("+8")); System.out.println("从1970-01-01到现在的总毫秒数:"+instant.toEpochMilli()); } 输出: 字符串转时间:2019-11-28T11:28:15 时间转字符串:2019-11-18 19:01:30 ================= 从1970-01-01到现在的总秒数:1574074890 从1970-01-01到现在的总毫秒数:1574074890568