zoukankan      html  css  js  c++  java
  • 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);
    
        }
    }
  • 相关阅读:
    C++ | Int转十六进制字符串
    Qt | QML Image SSL handshake failed
    《大话数据结构》第一章 数据结构绪论
    8组Beta冲刺4/5
    8组Beta冲刺1/5
    8组Beta冲刺3/5
    8组Beta冲刺2/5
    8组Beta冲刺5/5
    软工实践个人总结
    8组Beta冲刺总结
  • 原文地址:https://www.cnblogs.com/xiaoxiao075/p/13073863.html
Copyright © 2011-2022 走看看