Java8新日期API

代码

public class DateTestMain {

    public static void main(String... args) throws Exception {

        //当前日期时间
        LocalDateTime nowDateTime = LocalDateTime.now();
        //30分钟以前日期时间  对应minus*()的是plus*()
        LocalDateTime beforeDateTime = nowDateTime.minusMinutes(30L);

        System.out.println("【toString()方法】:" + beforeDateTime.toString());

        //日期格式:yyyy-MM-dd
        String dateStr = nowDateTime.toLocalDate().toString();
        //时间格式:HH:mm:ss.SSS
        String timeStr = nowDateTime.toLocalTime().toString();
        System.out.println("【日期】:" + dateStr);
        System.out.println("【时间】:" + timeStr);

        //转化成时间戳
        String dateTimePattern = "yyyy-MM-dd HH:mm:ss.SSS";
        long timeStamp = new SimpleDateFormat(dateTimePattern).parse(dateStr + " " + timeStr).getTime();
        System.out.println("【时间戳】:" + timeStamp);

        //日期格式必须是 yyyy-MM-dd
        LocalDate customDate = LocalDate.parse("2018-05-10");

        //几年前
        LocalDate beforeYearCustomDate = customDate.minusYears(2L);
        //几个月前
        LocalDate beforeMonthCustomDate = customDate.minusMonths(2L);
        //几周前
        LocalDate beforeWeekCustomDate = customDate.minusWeeks(4L);
        //几天前
        LocalDate beforeDayCustomDate = customDate.minusDays(4L);
        //没错!对应minus*()的是plus*(),很方便
//        LocalDate afterDayCustomDate = customDate.plusDays(4L);

        System.out.println("【几年前】:" + beforeYearCustomDate);
        System.out.println("【几个月前】:" + beforeMonthCustomDate);
        System.out.println("【几周前】:" + beforeWeekCustomDate);
        System.out.println("【几天前】:" + beforeDayCustomDate);
    }

}

打印结果

【toString()方法】:2018-05-30T16:47:33.905
【日期】:2018-05-30
【时间】:17:17:33.905
【时间戳】:1527671853905
【几年前】:2016-05-10
【几个月前】:2018-03-10
【几周前】:2018-04-12
【几天前】:2018-05-06


JDK版本(我用得是苹果的mac系统,这是jdk安装路径)

/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/bin/java

结语

更多功能就看api呗,抛砖引玉,原来计算时间挺麻烦的,已经升级到jdk8及以上版本的,了解一下。

你可能感兴趣的:(Java)