Java8 新时间日期类型

package com.xx;

import org.junit.Test;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author xx
 * DateTime: 2019/11/21 13:42
 * Description: Java8 时间与日期,这四种用法基本一样
 *      LocalDate:日期
 *      LocalTime:时间
 *      LocalDateTime:日期+时间
 *      Instant:计算机日期时间
 *
 *      Duration:计算2个时间之间的间隔
 *      Period:计算2个日期之间的间隔
 */
public class TimeTest {

    @Test
    public void test() {
        // 获取当前系统时间
        LocalDateTime now = LocalDateTime.now();
        System.out.println("当前时间:"+now);
        // 创建一个LocalDateTime类
        LocalDateTime of = LocalDateTime.of(2019, 11, 21, 14, 04);
        System.out.println("手动创建一个当前时间:"+of);
        // 时间格式化
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = now.format(formatter);
        System.out.println("格式化当前时间"+format);
        // 加一天
        System.out.println("加一天:"+of.plusDays(1));
        // 加一个月
        System.out.println("加一个月:"+of.plusMonths(1));
        // 减一天
        System.out.println("减一天:"+of.minusDays(1));
        // 减一个月
        System.out.println("减一个月:"+of.minusMonths(1));
        // 获得当前时间的年份
        System.out.println("获得当前时间的年份:"+of.getYear());
        // 获得当前时间的月份
        System.out.println("获得当前时间的月份:"+of.getMonth().getValue() + "或者" + of.getMonthValue());
        // 计算2个时间的差
        Long between = Duration.between(of, now).toMillis();
        System.out.println("计算2个时间的差:"+between);

    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章