jdk8中获取日期,时间,秒,毫秒值及格式化和与Date转化

看过易忘,留下备查

jdk8中对时间的获取方式进行了新的修改,常用的获取时间的方式为:

1: LocalDate.now()

2: LocalTime.now(),

3: LocalDateTime.now() ,

格式化时间:DateTimeFormatter.ofPattern();

获取当前时间戳有两种方式,本质上还是通过Instant获取:

1:LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMill();

2:Instant.now().toEpochMill()

        // 获取日期 和 时间 及格式化
        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();
        LocalDateTime localDateTime = LocalDateTime.now();
        String formatDateTime1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(localDateTime);
        String formatDateTime2 = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        System.out.println("localDate: " + localDate + "\n");
        System.out.println("localTime: " + localTime + "\n");
        System.out.println("localDateTime: " + localDateTime + "\n");
        System.out.println("formatDateTime1: " + formatDateTime1 + "\n");
        System.out.println("formatDateTime2: " + formatDateTime2 + "\n");

        // 获取秒值及毫秒值
        long epochSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).getEpochSecond();
        long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        long milliSeconds = Instant.now().toEpochMilli();
        long epochSeconds = Instant.now().getEpochSecond();

        System.out.println("epochSecond: " + epochSecond + "\n");
        System.out.println("milliSecond: " + milliSecond + "\n");
        System.out.println("epochSeconds: " + epochSeconds + "\n");
        System.out.println("milliSeconds: " + milliSeconds + "\n");

        // Date 与 LocalDateTime 及 String 之间的转换
        LocalDateTime dateToLocalDateTime = new Date().toInstant().atZone(ZoneId.of("+8")).toLocalDateTime();
        LocalDateTime parseToLocalDateTime = LocalDateTime.parse(formatDateTime1, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Date localDateTimeToDate = Date.from(LocalDateTime.now().toInstant(ZoneOffset.of("+8")));
        System.out.println("dateToLocalDateTime: " + dateToLocalDateTime + "\n");
        System.out.println("parseToLocalDateTime: " + parseToLocalDateTime + "\n");
        System.out.println("localDateTimeToDate: " + localDateTimeToDate + "\n");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值