1. 基本使用例子
package com.example.java8demo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Set;
/**
* java 8 对于日期和时间的使用
* API文档:https://blog.fondme.cn/apidoc/jdk-1.8-google/下的java.time包下
*/
@RunWith(SpringRunner.class)
@SpringBootTest // 指定启动类
public class LocalDateTimeTest {
/**
* localDate The operation of time
*/
@Test
public void test1(){
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("++++【localDateTime】++++"+localDateTime);
// -------iso 标准时间体系-------
LocalDateTime localDateTime1 = LocalDateTime.of(2018, 9, 25, 16, 46);
System.out.println("++++++【localDateTime1】+++++"+localDateTime1);
LocalDateTime localDateTime2 = localDateTime1.minusDays(20);
System.out.println("+++++++【localDateTime2】+++++++"+localDateTime2);
System.out.println("+++++++【localDateTime2.plusMonths(2)】+++++++++"+localDateTime2.plusMonths(2));
System.out.println("localDateTime2.getYear()"+localDateTime2.getYear());
System.out.println("localDateTime2.getMonthValue()"+localDateTime2.getMonthValue());
System.out.println("localDateTime2.getMonth()"+localDateTime2.getMonth());
System.out.println("localDateTime2.getDayOfWeek()"+localDateTime2.getDayOfWeek());
System.out.println("localDateTime2.getDayOfMonth()"+localDateTime2.getDayOfMonth());
System.out.println("localDateTime2.getHour()"+localDateTime2.getHour());
System.out.println("localDateTime2.getMinute()"+localDateTime2.getMinute());
System.out.println("localDateTime2.getSecond()"+localDateTime2.getSecond());
}
/**
* 2. Instant : 时间戳。 (使用 Unix 元年 1970年1月1日 00:00:00 所经历的毫秒值)
*/
@Test
public void test2(){
//默认使用 UTC 时区
Instant ins = Instant.now();
System.out.println(ins);
//偏移时区调整,时间偏移量8个小时
OffsetDateTime odt = ins.atOffset(ZoneOffset.ofHours(8));
System.out.println(odt);
System.out.println("++++ins.getNano()++++"+ins.getNano());
Instant ins2 = Instant.ofEpochSecond(5);
System.out.println("++++ins2++++"+ins2);
}
/**
* 计算时间间隔 Duration Period
* @throws InterruptedException
* toMillis()
*
*/
@Test
public void test3() throws InterruptedException{
Instant instantBegin = Instant.now();
Thread.sleep(2000);
Instant instantEnd = Instant.now();
System.out.println("输出当前时间间隔差"+ Duration.between(instantBegin, instantEnd).toMillis());
// -----------------------------------------------------------------------
LocalDate local1 = LocalDate.now();
LocalDate local2 = LocalDate.of(2016, 7, 23);
Period period = Period.between(local1, local2);
System.out.println("++++year++++"+period.getYears());
//月份单位不会按年份单位自动标准化。 这意味着“15个月”与“1年3个月”不同。查看api文档
System.out.println("++++month++++"+period.getMonths());
System.out.println("++++days++++"+period.getDays());
}
/**
* 时间校正器
* TemporalAdjuster
*/
@Test
public void test4(){
LocalDateTime ldt = LocalDateTime.now();
System.out.println("-----ldt-----"+ldt);
//表示为本月中的第几天
LocalDateTime ldt2 = ldt.withDayOfMonth(30);
System.out.println("----ldt2----"+ldt2);
//计算下周一的时间
LocalDateTime ldt3 = ldt.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
System.out.println("------ldt3-----"+ldt3);
//自定义:下一个工作日
LocalDateTime ldt4 = ldt.with((local) ->{
LocalDateTime ldt5 = (LocalDateTime) local;
DayOfWeek dow = ldt5.getDayOfWeek();
if(dow.equals(DayOfWeek.FRIDAY)){
return ldt5.plusDays(3);
}else if(dow.equals(DayOfWeek.SATURDAY)){
return ldt5.plusDays(2);
}else{
return ldt5.plusDays(1);
}
});
System.out.println("-------ldt4-----"+ldt4);
}
/**
* 5. DateTimeFormatter : 解析和格式化日期或时间
*/
@Test
public void test5(){
DateTimeFormatter dateTimeFormater = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("【----未格式化之前----】" + localDateTime);
System.out.println("【----格式化之后----】"+dateTimeFormater.format(localDateTime));
}
@Test
public void test6(){
// 获取可用时区
Set<String> set = ZoneId.getAvailableZoneIds();
set.forEach(System.out::println);
}
/**
* 7.ZonedDate、ZonedTime、ZonedDateTime : 带时区的时间或日期
*/
@Test
public void test7(){
LocalDateTime ldt = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
System.out.println("----【ldt】----"+ldt);
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("America/New_York"));
System.out.println("----【zdt】----"+zdt);
}
/**
* <B>备注:<B>
*
* zone 英[zəʊn]美[zoʊn]n.地带; 区域,范围; 地区,时区; [物] 晶带;vt. 划分成带; 用带子围绕;vi. 分成区,分成地带;
*
* available 英[əˈveɪləbl]美[əˈveləbəl]adj. 可获得的; 有空的; 可购得的; 能找到的;
*
* offset 美[ˈɔ:fset]vt. 抵消; 补偿; (为了比较的目的而)把…并列(或并置) ;
* 为(管道等)装支管;vi. 形成分支,长出分枝; 装支管;n. 开端; 出发; 平版印刷; 抵消,补偿;
*
* duration 美[duˈreɪʃn] n. 持续,持续的时间,期间; (时间的) 持续,持久,连续; [语音学] 音长,音延;
*
* instant 英[ˈɪnstənt] 美[ˈɪnstənt] n. 瞬间,顷刻; 此刻; 当月; 速食食品,即溶饮料; adj. 立即的; 迫切的; 正在考虑的,目前的; 即食的;
*
* temporal 英[ˈtempərəl] 美[ˈtɛmpərəl,ˈtɛmprəl] adj.时间的; 世俗的; 暂存的; <语>表示时间的; n.暂存的事物,世间的事物; 世俗的权力; 一时的事物,俗事;
*
* adjuster 英[ə'dʒʌstə] 美[ə'dʒʌstə] n.调停者,调节器;
*
*/
}
2. 封装工具类
package com.example.java8demo;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* @Title 日期时间工具类
* @Author lijingrun
* @Version 1.0.0
* @Date 2018/9/25 17:27
* @Description 使用JDK8新特性封装的日期时间工具类
*/
public class DateTimeUtils {
private static final ConcurrentMap<String, DateTimeFormatter> FORMATTER_CACHE = new ConcurrentHashMap<>();
private static final int PATTERN_CACHE_SIZE = 500;
/**
* Date转换为格式化时间
* @param date date
* @param pattern 格式
* @return
*/
public static String format(Date date, String pattern){
return format(LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()), pattern);
}
/**
* localDateTime转换为格式化时间
* @param localDateTime localDateTime
* @param pattern 格式
* @return
*/
public static String format(LocalDateTime localDateTime, String pattern){
DateTimeFormatter formatter = createCacheFormatter(pattern);
return localDateTime.format(formatter);
}
/**
* 格式化字符串转为Date
* @param time 格式化时间
* @param pattern 格式
* @return
*/
public static Date parseDate(String time, String pattern){
return Date.from(parseLocalDateTime(time, pattern).atZone(ZoneId.systemDefault()).toInstant());
}
/**
* 格式化字符串转为LocalDateTime
* @param time 格式化时间
* @param pattern 格式
* @return
*/
public static LocalDateTime parseLocalDateTime(String time, String pattern){
DateTimeFormatter formatter = createCacheFormatter(pattern);
return LocalDateTime.parse(time, formatter);
}
/**
* 在缓存中创建DateTimeFormatter
* @param pattern 格式
* @return
*/
private static DateTimeFormatter createCacheFormatter(String pattern){
if (pattern == null || pattern.length() == 0) {
throw new IllegalArgumentException("Invalid pattern specification");
}
DateTimeFormatter formatter = FORMATTER_CACHE.get(pattern);
if(formatter == null){
if(FORMATTER_CACHE.size() < PATTERN_CACHE_SIZE){
formatter = DateTimeFormatter.ofPattern(pattern);
//putIfAbsent,如果指定的键尚未与值相关联,请将其与给定值相关联。
DateTimeFormatter oldFormatter = FORMATTER_CACHE.putIfAbsent(pattern, formatter);
if(oldFormatter != null){
formatter = oldFormatter;
}
}
}
return formatter;
}
}
3. 参看文档
https://blog.fondme.cn/apidoc/jdk-1.8-google/下的java.time包下相关
https://wizardforcel.gitbooks.io/java8-tutorials/content/Java%208%20%E6%96%B0%E7%89%B9%E6%80%A7%E7%BB%88%E6%9E%81%E6%8C%87%E5%8D%97.html#datetimeAPI
[Java 8新的时间日期库的20个使用示例](https://wizardforcel.gitbooks.io/java8-tutorials/content/Java%208%20%E6%96%B0%E7%9A%84%E6%97%B6%E9%97%B4%E6%97%A5%E6%9C%9F%E5%BA%93%E7%9A%8420%E4%B8%AA%E4%BD%BF%E7%94%A8%E7%A4%BA%E4%BE%8B.html)