LocalDateTime、Date、String和时间戳Long互相转换

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class DateUtils {


    public static void main(String[] args) {
        //LocalDateTime转时间戳
        // 获取秒数
        long l = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
        System.out.println(l);
        // 获取毫秒数
        long l1 = LocalDateTime.now().toInstant(ZoneOffset.ofHours(+8)).toEpochMilli();
        System.out.println(l1);

        // 时间戳转LocalDateTime
        //1640878737155
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(1640878737155L), ZoneOffset.of("+8"));
        System.out.println(localDateTime.toString());

        //LocalDateTime 转String
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(FORMAT_ONE);
        String now = LocalDateTime.now().format(dateTimeFormatter);
        System.out.println(now);

        // String 转LocalDateTime
        LocalDateTime string2LocalDateTime = LocalDateTime.parse("2020-12-12 12:12:12", dateTimeFormatter);
        System.out.println(string2LocalDateTime);

        // LocalDateTime转Date
        Date date = new Date(LocalDateTime.now().toInstant(ZoneOffset.ofHours(+8)).toEpochMilli());;
        System.out.println(date);

        //Date 转LocalDateTime
        LocalDateTime localDateTime1 = new Date().toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
        LocalDateTime localDateTime2 = LocalDateTime.ofInstant(new Date().toInstant(), ZoneOffset.of("+8"));
        System.out.println(localDateTime1);
        System.out.println(localDateTime2);


    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值