java8引入了全新的时间类API,相比与之前的Date类操作上简化了许多,学习记录下。
package com.example.java8.date;
import org.junit.Test;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class Jave8DateTest {
/**
* 获取当前日期
*/
@Test
public void test1() {
//获取今天的日期 2020-05-06
LocalDate today = LocalDate.now();
System.out.println("今天的日期:" + today);
//2020-05-06T19:57:42.545
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime);
//判断2个日期时间是否相等
LocalDate date1 = LocalDate.now();
LocalDate date2 = LocalDate.of(2020, 5, 6);
System.out.println("自定义日期:" + date2);
if (date1.equals(date2)) {
System.out.println("时间相等");
} else {
System.out.println("时间不等");
}
}
/**
* 获取当前时间
*/
@Test
public void test2() {
//当前时间
LocalTime time = LocalTime.now();
//当前时间4个小时后的时间
LocalTime newTime = time.plusHours(4);
System.out.println("三个小时后的时间为:" + newTime);
//当前日期
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
//当前日期4个小时候的日期
LocalDateTime localDateTime = now.plusHours(4);
System.out.println(localDateTime);
}
/**
* 一周后的日期
*/
@Test
public void test3() {
LocalDate today = LocalDate.now();
System.out.println("今天的日期为:" + today);
LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
System.out.println("一周后的日期为:" + nextWeek);
}
/**
* 获取当前系统的时间戳
*/
@Test
public void test4() {
Clock clock = Clock.systemUTC();
Clock defaultClock = Clock.systemDefaultZone();
System.out.println("Clock : " + clock.millis());
System.out.println("Clock : " + defaultClock.millis());
}
/**
* 判断日期先后顺序
*/
@Test
public void test5() {
LocalDate today = LocalDate.now();
System.out.println("今天的日期:" + today);
LocalDate tomorrow = LocalDate.of(2020, 5, 7);
System.out.println("tomorrow 在today后面吗? " + tomorrow.isAfter(today));
LocalDate yesterday = today.minus(1, ChronoUnit.DAYS);
System.out.println("yestoday 在today前面吗? " + yesterday.isBefore(today));
}
/**
* 计算两个日期间的天数,月数
*/
@Test
public void test6() {
LocalDate today = LocalDate.now();
LocalDate someDay = LocalDate.of(2020, 6, 17);
Period period = Period.between(today, someDay);
//相差天数
System.out.println("day:" + period.getDays());
//相差月数,取整
System.out.println("month:" + period.getMonths());
}
/**
* 格式化日期
*/
@Test
public void test7(){
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime date = LocalDateTime.now();
String formatDate = date.format(format1);
System.out.println("格式化后的日期为:" + formatDate);
String dateStr = "2020-05-06 20:34:03";
DateTimeFormatter format2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDate = LocalDateTime.parse(dateStr, format2);
System.out.println(localDate);
}
}