Java8的日期时间处理

代码:

package com.ufo.java8datetime;

import java.time.Clock;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class Java8DateTime {
    public static void main(String[] args) {
        // 取今天日期
        LocalDate today=LocalDate.now();
        System.out.println("Today's date="+today);
        System.out.println("Today's year="+today.getYear());
        System.out.println("Today's month="+today.getMonthValue());
        System.out.println("Today's day="+today.getDayOfMonth());
        
        // 特定日期
        LocalDate devoiceDay=LocalDate.of(2020, 1, 16);
        System.out.println("Devoice date="+devoiceDay);
        
        // 日期相等比较
        if(today.equals(devoiceDay)==false) {
            System.out.println("today !=devoiceDay ");
        }
        
        // 一周后
        LocalDate aWeekLater=today.plus(1, ChronoUnit.WEEKS);
        System.out.println("A week later="+aWeekLater);
        
        // 一年前
        LocalDate aYearBefore=today.plus(-1, ChronoUnit.YEARS);
        System.out.println("A Year before="+aYearBefore);
        
        // 日期比较
        LocalDate longAgo=LocalDate.of(2000, 1, 1);
        if(longAgo.isBefore(aYearBefore)) {
            System.out.println(longAgo+" is before "+aYearBefore);
        }
        
        // 日期比较
        if(today.isAfter(aYearBefore)) {
            System.out.println(today+" is after "+aYearBefore);
        }
        
        // 年份差
        Period years=Period.between(longAgo, aYearBefore);
        System.out.println("There are "+years.getYears()+" years between "+longAgo+" "+aYearBefore);
        
        // 当前时间
        LocalTime currTime=LocalTime.now();
        System.out.println("Current time="+currTime);
        
        // 时间加
        LocalTime threehoursLater=currTime.plusHours(3);
        System.out.println("3 hours later="+threehoursLater);
        
        // 取毫秒时间戳
        Clock clock=Clock.systemUTC();
        System.out.println(clock.millis()+" == "+System.currentTimeMillis());
        
        // 日期转字符串
        DateTimeFormatter format1=DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        System.out.println(today.format(format1));
        
        // 字符串转日期
        LocalDate date1=LocalDate.parse("1644年03月14日", format1);
        System.out.println(date1);
    }
}

输出:

Today's date=2020-01-20
Today's year=2020
Today's month=1
Today's day=20
Devoice date=2020-01-16
today !=devoiceDay 
A week later=2020-01-27
A Year before=2019-01-20
2000-01-01 is before 2019-01-20
2020-01-20 is after 2019-01-20
There are 19 years between 2000-01-01 2019-01-20
Current time=20:40:57.528
3 hours later=23:40:57.528
1579524057528 == 1579524057528
2020年01月20日
1644-03-14

2020年1月20日

posted @ 2020-01-20 20:47  逆火狂飙  阅读(409)  评论(0编辑  收藏  举报
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东