java日期 Date、LocalDateTime转化等

import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalField;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class TestDate {
    public static void main(String[] args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
        System.out.println(new Date().after(sdf.parse("2019-05-01 16:12:59")));

        //设置日期转化格式
        DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
        //LocalDateTime转换为java.Util.Date
        LocalDateTime localDateTime=LocalDateTime.now();
        //方式一:
        ZonedDateTime zonedDateTime=localDateTime.atZone(ZoneId.systemDefault());
        Instant instant=Instant.from(zonedDateTime);
        Date date=Date.from(instant);
        Date date1=new Date(instant.toEpochMilli());

        //方式二:
        Instant inst=localDateTime.toInstant(ZoneOffset.of("+8"));
        Instant inst1=localDateTime.toInstant(ZoneOffset.ofHours(8));
        Date date2=Date.from(inst);

        //LocalDate转换为Date类型
        LocalDate localDate=LocalDate.now();
        Instant inst3=Instant.from(localDate.atStartOfDay(ZoneId.systemDefault()));
        Date date3=Date.from(inst3);
        System.out.println("date3:"+date3);

        //时间戳打印
        System.out.println(instant.toEpochMilli());
        System.out.println(System.currentTimeMillis());

        //字符串转换为LocalDateTime
        String dateStr="2020-06-09 15:07:22.325";
        LocalDateTime localDateTime1=LocalDateTime.parse(dateStr,dateTimeFormatter);

        //Date类型转换为 LocalDateTime类型
        Instant instant2=date.toInstant();
        LocalDateTime localDateTime2=LocalDateTime.ofInstant(instant2,ZoneId.systemDefault());
        System.out.println("localDatetime2:"+localDateTime2);

    }
}

 

posted @ 2020-06-09 17:10  小金儿  阅读(1981)  评论(0编辑  收藏  举报