Java8 学习笔记(三)—— 新时间API

先来一段代码,看看传统的日期格式化与java8有什么不同

	public static void main(String[] args) {
		
		//传统日期格式化
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		System.out.println(format.format(new Date()));
		
		//java8
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
		System.out.println(LocalDate.now().format(formatter));
	}

乍看之下,无非就是使用的类发生了变化而已,其实不然。我们知道SimpleDateFormat是非线程安全的,通常会结合ThreadLocal来使用;但是java8的DateTimeFormatter是线程安全的,可以直接使用;java8时间相关的类都放在了java.time.*这个包下。下面让我们看看新的时间API有哪些。

package cn.fg.time;

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Set;

import org.junit.Test;

public class Tester {
	
	DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
	
	/**
	 * LocalDate 日期
	 * LocalTime 时间
	 * LocalDateTime 日期与时间
	 * 都 implements Temporal
	 */
	
	@Test
	public void test1(){
		DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("HH:mm:ss");
		DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		
		//输出当前时间的字符串格式
		String dateString = LocalDate.now().format(formatter1);  //只能选择formatter1,否则报错
		String timeString = LocalTime.now().format(formatter2);  //只能选择formatter2,否则报错
		String dateTimeString = LocalDateTime.now().format(formatter3); //三种formatter都可以选择
		
		System.out.println(dateString);  
		System.out.println(timeString);  
		System.out.println(dateTimeString); 
		
		//字符串转为对应的时间类
		LocalDate date = LocalDate.parse(dateString, formatter1);
		LocalTime time = LocalTime.parse(timeString,formatter2);
		LocalDateTime dateTime = LocalDateTime.parse(dateTimeString,formatter3);
		
		//getXXX()
		//toXXX()
		System.out.println(date.getYear());   
		System.out.println(time.getHour());
		System.out.println(dateTime.toLocalDate());  
		
		
		//如果不使用format方法输出,则按照iso 8601格式输出
		System.out.println(LocalDateTime.now()); //调用toString()
	
	}
	
	
	//Instant 时间戳   implements Temporal
	@Test
	public void test2(){
		Instant now = Instant.now();
        System.out.println(now.getEpochSecond()); //秒       输出1595505736
        System.out.println(now.toEpochMilli());   //毫秒   输出1595505736551
        System.out.println(now.getNano());        //纳秒   输出551000000,纳秒=当前时间点的毫秒数(551)*1000000
	}
	
	/*
	 * Duration 用于计算两个时间间隔
	 * Period   用于计算两个日期间隔
	 */
	
	@Test
	public void test3(){
		LocalTime time1 = LocalTime.of(20, 30, 15);          //of() 指定具体时间
		LocalTime time2 = LocalTime.of(20, 30, 30);
		Duration duration = Duration.between(time1, time2);  //也可以放时间戳
		System.out.println(duration.toHours());
		System.out.println(duration.toMinutes());
		System.out.println(duration.getSeconds());
		
		LocalDate date1 = LocalDate.of(2020, 1, 20);        //of() 指定具体日期
		LocalDate date2 = LocalDate.of(2020, 1, 30);
		Period period = Period.between(date1, date2);
		System.out.println(period.getYears());
		System.out.println(period.getMonths());
		System.out.println(period.getDays());
	}
	
	//ZonedDate、ZonedTime、ZonedDateTime : 带时区的时间或日期
	@Test
	public void test4(){
		
		LocalDateTime ldt = LocalDateTime.now(ZoneId.systemDefault());  //操作系统默认时区,不写ZoneId.systemDefault()也是默认值
		System.out.println(ldt.format(formatter));
		
		ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("US/Pacific")); 
		System.out.println(zdt.format(formatter));
		
		ZonedDateTime zbj = ZonedDateTime.now(); 
		ZonedDateTime zny = ZonedDateTime.now(ZoneId.of("America/New_York")); 
		System.out.println(zbj.format(formatter));
		System.out.println(zny.format(formatter));
		
		Set set = ZoneId.getAvailableZoneIds();  //查看所有时区
		set.forEach(System.out::println);
	}
	
	//TemporalAdjuster : 时间校正器
	@Test
	public void test5(){
	LocalDateTime ldt = LocalDateTime.now();
		System.out.println(ldt);
		
		LocalDateTime ldt2 = ldt.withDayOfMonth(10);
		System.out.println(ldt2);
		
		LocalDateTime ldt3 = ldt.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
		System.out.println(ldt3);
		
		//自定义:下一个工作日
		LocalDateTime ldt5 = ldt.with((l) -> {
			LocalDateTime ldt4 = (LocalDateTime) l;
			
			DayOfWeek dow = ldt4.getDayOfWeek();
			
			if(dow.equals(DayOfWeek.FRIDAY)){
				return ldt4.plusDays(3);
			}else if(dow.equals(DayOfWeek.SATURDAY)){
				return ldt4.plusDays(2);
			}else{
				return ldt4.plusDays(1);
			}
		});
		
		System.out.println(ldt5);
		
	}
	
}

最佳实践:https://www.liaoxuefeng.com/wiki/1252599548343744/1303978948165666 

Java8 学习笔记(三)—— 新时间API_第1张图片

Java8 学习笔记(三)—— 新时间API_第2张图片

你可能感兴趣的:(java8)