java8日期demo

136 阅读4分钟
常用日期总结:

Date date = new Date();

//Date -> LocalDate
LocalDate localDate = date.toInstant()
        .atZone(ZoneId.systemDefault()).toLocalDate();
        
//Date -> LocalDateTime

LocalDateTime localDateTime = date.toInstant()
        .atZone(ZoneId.systemDefault()).toLocalDateTime();
System.out.println("localDate = " + localDate);
System.out.println("localDateTime = " + localDateTime);

//LocalDateTime -> Date
Date from = Date
    .from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
System.out.println("from = " + from);

String -> LocalDateTime:
String timeStr = "2022/6/20" 
LocalDate parse = LocalDate.parse(timeStr, DateTimeFormatter.ofPattern("yyyy/M/dd"));

//LocalDateTime -> String:
LocalDateTime now = LocalDateTime.now();
String s = now.toString();  // //s = 2022-06-20T18:42:35.332

// 格式化
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");  
String now = LocalTime.now().atDate(LocalDate.now()).format(formatter);   // 2023-08-02 11:57:51

// 获取当前时间 
LocalDate localDate = LocalDate.now();   // yy-MM-dd
String localDate = localDate.toString();

//获取LocalTime LocalTime localTime = localDateTime.toLocalTime();  // yy-MM-dd hh:mm:ss

// 输入年月日设置时间 
LocalDate localDate = LocalDate.of(year,month,day);

// 获取年月日星期几
int year = localDate.getYear();
int year = localDate.get(ChronoField.YEAR);

//注意getMonth方法返回的是Month类,可通过getValue方法获得一个long类型的值,然后可以强转为int类型进行使用
Month month = localDate.getMonth();
int month1 = localDate.get(ChronoField.MONTH_OF_YEAR);
int day = localDate.getDayOfMonth();
int day1 = localDate.get(ChronoField.DAY_OF_MONTH);
//注意getDayOfWeek方法返回的是DayOfWeek类,可通过getValue方法获得一个long类型的值,然后可以强转为int类型进行使用
DayOfWeek dayOfWeek = localDate.getDayOfWeek();
int dayOfWeek1 = localDate.get(ChronoField.DAY_OF_WEEK);

//增加一年
localDate = localDate.plusYears(1);
localDate = localDate.plus(1, ChronoUnit.YEARS);
//减少一个月
localDate = localDate.minusMonths(1);
localDate = localDate.minus(1, ChronoUnit.MONTHS);
//减少一日
localDate = localDate.minusDays(1);
localDate = localDate.minus(1, ChronoUnit.DAYS);

//通过使用with方法进行修改
//修改年为2020
localDate = localDate.withYear(2020);
//修改为2020
localDate = localDate.with(ChronoField.YEAR, 2020);
package cn.nice.h2.base;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import org.junit.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @Description localDate : 主要用于处理日期的 java8 特性之一
 * @Author nice
 * @Date 2021/9/22 4:33 下午
 */

public class LocalDateDemo {

    @Test
    public void test1(){

        System.out.println(LocalDateTime.now().toEpochSecond(ZoneOffset.ofHours(8)));

        System.out.println("!!!!!!!");
        LocalDate localDate = LocalDate.now();         // 2021-09-22

        // System.out.println(localDate.toString());   // 2021-09-22
        LocalDateTime localDateTime = LocalDateTime.now();
        // System.out.println(localDateTime);  // 2021-09-22T16:54:34.869
        // System.out.println(localDateTime.toLocalTime());   // 16:55:48.355
        System.out.println(localDateTime.toString());         // 2021-09-22T17:31:45.509
        LocalDate localDate1 = LocalDate.of(2020,12,3);
        // System.out.println(localDate1);    // 2020-12-03
        System.out.println(localDate1.getYear());    // 2020
        System.out.println(localDate1.getMonth().getValue());  // 12

        DayOfWeek dayOfWeek = localDate.getDayOfWeek();
        // System.out.println(dayOfWeek.getValue());         //  获取星期: 3
        // System.out.println(localDate.getMonth().getValue());      //  获取月份:  9

        Boolean isLeapYear = localDate.isLeapYear();    // 获取当前日期所在年是否是闰年


        /**
         * with开头的方法,我的理解是将参数替换localDate中的对应
         * 属性,重新计算得到新的日期。
         * 将参数中的"日"替换localDate中的"日"
         * 将参数中的天数替换localDate中的天数
         * 将参数中的"月"替换localDate中的"月"
         * 将参数中的"年"替换localDate中的"年"
         * */
        localDate = LocalDate.of(2019,1,7);
        System.out.println(localDate.withDayOfMonth(2));  // 2019-01-02
        System.out.println(localDate.withDayOfYear(40));  // 2019-02-09
        System.out.println(localDate.withMonth(2));       // 2019-02-07
        System.out.println(localDate.withYear(2020));     // 2020-01-07


        Period weeks = Period.ofWeeks(2);
        Period years = Period.ofYears(2);
        System.out.println(localDate.minus(weeks));       // 2019-01-07 - > 2018-12-24 (2周前)
        System.out.println(localDate.plus(weeks));       // 2019-01-07 - > 2019-01-21(2周后)

        /**
         * localDate.minusDays(long days)
         * localDate.minusWeeks(long weeks)
         * localDate.minusMonths(long months)
         * localDate.minusYears(long years)
         * localDate.plusDays(long days)
         * localDate.plusWeeks(long weeks)
         * localDate.plusMonths(long months)
         * localDate.plusYears(long years)
         * */
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String now = LocalTime.now().atDate(LocalDate.now()).format(formatter);
        System.out.println(LocalTime.now().atDate(LocalDate.now()).format(formatter));  // 2021-09-22 17:40:30
        System.out.println(LocalDate.now().atTime(LocalTime.now()).format(formatter));   // 2021-09-22 17:40:30
        String s = localDateTime.format(formatter);   // 2021-09-22 17:40:30
        System.out.println(s);

    }
    /** 使用转换日期判定日期是否符合正确日期 */
    public static boolean isValidDate(String str) {
        boolean convertSuccess=true;
        // 指定日期格式为四位年/两位月份/两位日期,注意yyyy/MM/dd区分大小写;
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        try {
        // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
            format.setLenient(false);
            format.parse(str);
        } catch (ParseException e) {
            // e.printStackTrace();
            // 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
            convertSuccess=false;
        }
        return convertSuccess;
    }

    /**
     *
     * LocalDateTime 为java8的新特性之一
     * LocalDateTime.now() 获得当前时间
     * java.time.Duration duration = java.time.Duration.between(LocalDateTime   startTime,  LocalDateTime  endTime );
     * 例如:     duration.toMinutes()    //两个时间差的分钟数
     * toNanos()//纳秒
     * toMillis()//毫秒
     * toMinutes()//分钟
     * toHours()//小时
     * toDays()//天数
     * */

    public static Long durationDay(String startDateStr,String endDateStr) {
        if(startDateStr.length() >= 10){
            startDateStr = startDateStr.substring(0,10);
        }
        if(endDateStr.length() >= 10){
            endDateStr = endDateStr.substring(0,10);
        }
        startDateStr += " 00:00:00";
        endDateStr += " 00:00:00";
        // LocalDateTime必须是yyyy-MM-dd HH:mm:ss
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startDate = LocalDateTime.parse(startDateStr,dateTimeFormatter);
        LocalDateTime endDate = LocalDateTime.parse(endDateStr,dateTimeFormatter);
        return Duration.between(startDate, endDate).toDays();
    }
    public static Long DateUtilDurationDay(String startDateStr,String endDateStr) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        try {
            // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
            format.setLenient(false);
            return DateUtil.between(format.parse(startDateStr), format.parse(endDateStr), DateUnit.DAY);
        } catch (ParseException e) {
            // e.printStackTrace();
            // 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
            Assert.isFalse(false,"传递日期有问题");
        }
        return 0l;
    }
    public static void main(String[] args) {

        System.out.println(DateUtilDurationDay("2021-01-01","2021-01-03"));

    }

}