• Java8 日期时间API


    一、转换

    1、与字符串

    //LocalDateTime 转 字符串
    String str = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());
    //字符串 转 LocalDateTime 
     LocalDateTime localDateTime = LocalDateTime.parse("2019-06-26 19:00:00",
                                              DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

    2、与Date

    // Date 转 LocalDateTime 与 LocalDate
    Date date = new Date();
    Instant instant = date.toInstant();
    ZoneId zoneId = ZoneId.systemDefault();
    LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
    LocalDate localDate = instant.atZone(zoneId).toLocalDate();
    //也可以使用LocalDateTime的FactoryInput()方法使用系统的默认时区
    LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), zoneId);
    ------------------------------------------------------------------------------------------------
    // LocalDateTime 转换成 Date
    ZoneId zoneId = ZoneId.systemDefault();
    ZonedDateTime zdt = localDateTime.atZone(zoneId);
    Date date = Date.from(zdt.toInstant());
    // LocalDate 转换成 Date
    ZoneId zoneId = ZoneId.systemDefault();
    ZonedDateTime zdt = localDate.atStartOfDay(zoneId);
    Date date = Date.from(zdt.toInstant());

    3、LocalDateTime 转 LocalDate

    LocalDateTime now = LocalDateTime.now();
    LocalDate localDate = now.toLocalDate();

    二、比较

    String time1 = "2019-06-26 19:00:00";
    DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime localDateTime = LocalDateTime.parse(time1, dtf2);
    System.out.println(localDateTime.isBefore(LocalDateTime.now()));//如果你的时间在当前时间之前,那么就是true
    System.out.println(localDateTime.isAfter(LocalDateTime.now()));//反之是否在当前时间之后就是false

    三、计算日期时间差

    在Java8中,我们可以使用以下类来计算日期时间差异:

    1.Period
    2.Duration
    3.ChronoUnit

    1、Period类

    主要是Period类方法getYears(),getMonths()和getDays()来计算.

    示例:

    import java.time.LocalDate;
    import java.time.Month;
    import java.time.Period;
    public class Test {
        public static void main(String[] args) {
            LocalDate today = LocalDate.now();
            System.out.println("Today : " + today);
            LocalDate birthDate = LocalDate.of(1993, Month.OCTOBER, 19);
            System.out.println("BirthDate : " + birthDate);
            Period p = Period.between(birthDate, today);
            System.out.printf("年龄 : %d 年 %d 月 %d 日", p.getYears(), p.getMonths(), p.getDays());
        }
    }

    结果:

    Today : 2017-06-16
    BirthDate : 1993-10-19
    年龄 : 23 年 7 月 28 日

    2、Duration类

    提供了使用基于时间的值(如秒,纳秒)测量时间量的方法。

    示例:

    LocalDateTime now = LocalDateTime.now();
    Duration duration = Duration.between(now,now);
        long days = duration.toDays(); //相差的天数
        long hours = duration.toHours();//相差的小时数
        long minutes = duration.toMinutes();//相差的分钟数
        long millis = duration.toMillis();//相差毫秒数
        long nanos = duration.toNanos();//相差的纳秒数
        System.out.println(millis);

    3、ChronoUnit类

    ChronoUnit类可用于在单个时间单位内测量一段时间,例如天数或秒。以下是使用between()方法来查找两个日期之间的区别的示例。

    示例:

    public static void main(String[] args) {
        String str1 = "2019-11-18 12:10:01";
        String str2 = "2019-11-18 14:12:09";
        LocalDateTime date1 = LocalDateTime.parse(str1, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        LocalDateTime date2 = LocalDateTime.parse(str2, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    
        Duration duration = Duration.between(date1, date2);
        System.out.println(duration);
        long days = duration.toDays(); //相差的天数
        long hours = duration.toHours();//相差的小时数
        long minutes = duration.toMinutes();//相差的分钟数
        long seconds = duration.toMillis() / 1000;//相差秒数
        System.out.println(String.format("%s小时%s分%s秒", hours, minutes - hours * 60, seconds - minutes * 60));
    
        System.out.println("-----------------------------------------");
        long d = ChronoUnit.DAYS.between(date1, date2);  //相差的天数
        long h = ChronoUnit.HOURS.between(date1, date2); //相差的小时数
        long m = ChronoUnit.MINUTES.between(date1, date2); //相差的分钟数
        long s = ChronoUnit.SECONDS.between(date1, date2); //相差秒数
        System.out.println(String.format("%s小时%s分%s秒", h, m - h * 60, s - m * 60));
    }

    输出结果:

    PT2H2M8S
    2小时2分8秒
    -----------------------------------------
    2小时2分8秒
    
    Process finished with exit code 0

    四、日期格式化

    JDK8之前:SimpleDateFormat来进⾏格式化,但SimpleDateFormat并不是线程安全的

    JDK8之后:引⼊线程安全的⽇期与时间DateTimeFormatter

    LocalDateTime ldt = LocalDateTime.now();
    System.out.println(ldt);
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    String ldtStr = dtf.format(ldt);
    System.out.println(ldtStr);

    获取指定的⽇期时间对象

    LocalDateTime ldt = LocalDateTime.of(2020, 11, 11, 8, 20, 30);
    System.out.println(ldt);

    五、常用API

    public static void main(String[] args) {
            System.out.println("当前日期:");
            LocalDate currentDate = LocalDate.now();
            System.out.println(currentDate);
            System.out.println("----------------------------------");
            System.out.println("当天周日期:");
            String currentDayOfWeek = currentDate.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.CHINA);
            System.out.println(currentDayOfWeek);
            System.out.println(currentDate.getDayOfWeek().getValue());
            System.out.println("----------------------------------");
            System.out.println("当月第一天日期:");
            LocalDate firstDayOfMonth = currentDate.with(TemporalAdjusters.firstDayOfMonth());
            System.out.println(firstDayOfMonth);
            System.out.println("----------------------------------");
            System.out.println("当月最后一天日期:");
            LocalDate lastDayOfMonth = currentDate.with(TemporalAdjusters.lastDayOfMonth());
            System.out.println(lastDayOfMonth);
            System.out.println("----------------------------------");
            System.out.println("当月最后一天周日期:");
            String lastDayOfWeek = lastDayOfMonth.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.CHINA);
            System.out.println(lastDayOfWeek);
            System.out.println("----------------------------------");
            System.out.println("当前日期后天周日期(数字):");
            System.out.println(currentDate.plusDays(2).getDayOfWeek().getValue());
        }

  • 相关阅读:
    解决Ubuntu下gedit中文乱码
    Linux下安装Matlab软件
    3.5mm耳机/麦克接头
    IIS无法加载PHP.ini
    修改mysql用户密码
    dhtmlxgrid使用基础
    远程桌面“终端服务器超出了最大允许连接数”的解决
    MATLAB中格式化M文件注释
    MATLAB中使用Cell对M文件分节
    MATLAB下一些常用易忘命令
  • 原文地址:https://www.cnblogs.com/better-farther-world2099/p/11912052.html
Copyright © 2020-2023  润新知