使用LocalDate德玫、LocalTime键兜、LocalDateTime
LocalDate膘螟、LocalTime成福、LocalDateTime 類(lèi)的實(shí)例是不可變的對(duì)象,分別表示使用 ISO-8601日歷系統(tǒng)的日期荆残、時(shí)間奴艾、日期和時(shí)間。它們提供了簡(jiǎn)單的日期或時(shí)間内斯,并不包含當(dāng)前的時(shí)間信息蕴潦。也不包含與時(shí)區(qū)相關(guān)的信息
注:ISO-8601日歷系統(tǒng)是國(guó)際標(biāo)準(zhǔn)化組織制定的現(xiàn)代公民的日期和時(shí)間的表示法
image.png
Instant 時(shí)間戳
用于“時(shí)間戳”的運(yùn)算。它是以Unix元年(傳統(tǒng) 的設(shè)定為UTC時(shí)區(qū)1970年1月1日午夜時(shí)分)開(kāi)始 所經(jīng)歷的描述進(jìn)行運(yùn)算
Duration 和 Period
- Duration:用于計(jì)算兩個(gè)“時(shí)間”間隔
- Period:用于計(jì)算兩個(gè)“日期”間隔
日期的操縱
-
TemporalAdjuster : 時(shí)間校正器俘闯。
- 有時(shí)我們可能需要獲 取例如:將日期調(diào)整到“下個(gè)周日”等操作潭苞。
-
TemporalAdjusters: 該類(lèi)通過(guò)靜態(tài)方法提供了大量的常用 TemporalAdjuster 的實(shí)現(xiàn)。
- 例如獲取下個(gè)周日:
image.png
解析與格式化
java.time.format.DateTimeFormatter類(lèi):該類(lèi)提供了三種 格式化方法:
- 預(yù)定義的標(biāo)準(zhǔn)格式
- 語(yǔ)言環(huán)境相關(guān)的格式
- 自定義的格式
時(shí)區(qū)的處理
- Java8 中加入了對(duì)時(shí)區(qū)的支持备徐,帶時(shí)區(qū)的時(shí)間為分別為:
- ZonedDate萄传、ZonedTime、ZonedDateTime
- 其中每個(gè)時(shí)區(qū)都對(duì)應(yīng)著 ID蜜猾,地區(qū)ID都為 “{區(qū)域}/{城市}”的格式
- 例如 :Asia/Shanghai 等
- ZoneId:該類(lèi)中包含了所有的時(shí)區(qū)信息
- getAvailableZoneIds() : 可以獲取所有時(shí)區(qū)時(shí)區(qū)信息
- of(id) : 用指定的時(shí)區(qū)信息獲取ZoneId 對(duì)象
與傳統(tǒng)日期處理的轉(zhuǎn)換
image.png
代碼演示
DateFormatThreadLocal
package com.www.java8.data;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* SimpleDateFormat 上鎖秀菱, 解決線程問(wèn)題
* <p>
*
* @author Www
* <p>
* 郵箱: 483223455@qq.com
* <p>
* 創(chuàng)建時(shí)間: 2022/8/13 16:35 星期六
* <p>
*/
public class DateFormatThreadLocal {
private static final ThreadLocal<DateFormat> dateFormat = new ThreadLocal<>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};
public static Date convert(String source) throws ParseException {
return dateFormat.get().parse(source);
}
}
DateTimeFormatterTest
package com.www.java8.data;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
/**
* SimpleDateFormat 存在線程安全問(wèn)題
* <p>
*
* @author Www
* <p>
* 郵箱: 483223455@qq.com
* <p>
* 創(chuàng)建時(shí)間: 2022/8/13 16:26 星期六
* <p>
*/
public class DateTimeFormatterTest {
/**
* 方法入口
*
* @param args 參數(shù)
*/
public static void main(String[] args) throws ExecutionException, InterruptedException {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE;
Callable<LocalDate> callable = () -> LocalDate.parse("2013-09-09", dateTimeFormatter);
ExecutorService pool = Executors.newFixedThreadPool(10);
List<Future<LocalDate>> results = new ArrayList<>();
for (int i = 0; i < 10; i++) {
results.add(pool.submit(callable));
}
for (Future<LocalDate> result : results) {
System.out.println(result.get());
}
pool.shutdown();
}
}
LocalDateTimeTest
package com.www.java8.data;
import org.junit.Test;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Set;
/**
* <p>
*
* @author Www
* <p>
* 郵箱: 483223455@qq.com
* <p>
* 創(chuàng)建時(shí)間: 2022/8/13 16:51 星期六
* <p>
*/
public class LocalDateTimeTest {
/**
* 1、LocalDate 【時(shí)間】 LocalTime【日期】 LocalFDateTime 【時(shí)間和日期】
*/
@Test
public void test1() {
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime);
LocalDateTime of = LocalDateTime.of(2020, 8, 13, 10, 30, 20, 30);
System.out.println("of = " + of);
LocalDateTime localDateTime1 = localDateTime.plusYears(10);
System.out.println("localDateTime1 = " + localDateTime1);
System.out.println("localDateTime.minusYears(5) = " + localDateTime.minusYears(5));
System.out.println("localDateTime.getYear() = " + localDateTime.getYear());
System.out.println("localDateTime.getMonthValue() = " + localDateTime.getMonthValue());
System.out.println("localDateTime.getDayOfMonth() = " + localDateTime.getDayOfMonth());
System.out.println("localDateTime.getHour() = " + localDateTime.getHour());
System.out.println("localDateTime.getMinute() = " + localDateTime.getMinute());
System.out.println("localDateTime.getSecond() = " + localDateTime.getSecond());
}
/**
* 2蹭睡、Instant :時(shí)間戳 ( 以 Unix 元年 : 1970 年 1月1日 00:00:00 某個(gè)是時(shí)間之間的毫秒數(shù))
*/
@Test
public void test2() {
// 默認(rèn)獲取 utc(格林尼治時(shí)間) 時(shí)區(qū)
Instant now = Instant.now();
System.out.println("now = " + now);
OffsetDateTime offsetDateTime = now.atOffset(ZoneOffset.ofHours(8));
System.out.println(offsetDateTime);
long s = offsetDateTime.toEpochSecond();
long m = offsetDateTime.toInstant().toEpochMilli();
System.out.println("s = " + s);
System.out.println("m = " + m);
Instant instant = Instant.ofEpochSecond(1000);
System.out.println("Instant.MIN = " + Instant.MAX);
System.out.println("instant = " + instant);
}
/**
* Duration : 計(jì)算兩個(gè) "時(shí)間" 之間的間隔
*/
@Test
public void test3() {
Instant now = Instant.now();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
Instant now1 = Instant.now();
Duration between = Duration.between(now, now1);
System.out.println("between = " + between);
System.out.println("******************************************");
LocalTime now2 = LocalTime.now();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
LocalTime now3 = LocalTime.now();
System.out.println("Duration.between(now2, now3).toMillis() = " + Duration.between(now2, now3).toMillis());
}
/**
* Period : 計(jì)算兩個(gè) "日期" 之間的間隔
*/
@Test
public void test4() {
LocalDate of = LocalDate.of(2022, 8, 9);
LocalDate of1 = LocalDate.of(22, 6, 9);
Period between = Period.between(of, of1);
System.out.println("between = " + between);
System.out.println("between.getYears() = " + between.getYears());
System.out.println("between.getMonths() = " + between.getMonths());
System.out.println("between.getDays() = " + between.getDays());
System.out.println("between.getUnits() = " + between.getUnits());
}
/**
* TemporalAdjuster :時(shí)間矯正器
*/
@Test
public void test5() {
LocalDateTime now = LocalDateTime.now();
System.out.println("now = " + now);
LocalDateTime localDateTime = now.withDayOfMonth(8);
System.out.println("localDateTime = " + localDateTime);
System.out.println("now.withDayOfMonth(10) = " + now.withDayOfMonth(5));
LocalDateTime with = now.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
System.out.println("with = " + with);
// 獲取下一個(gè)工作日
LocalDateTime with1 = now.with(l -> {
LocalDateTime l2 = (LocalDateTime) l;
DayOfWeek dayOfWeek = l2.getDayOfWeek();
if (dayOfWeek.equals(DayOfWeek.FRIDAY)) {
return l2.plusDays(3);
} else if (dayOfWeek.equals(DayOfWeek.SATURDAY)) {
return l2.plusDays(2);
} else {
return l2.plusDays(1);
}
});
System.out.println("with1 = " + with1);
}
/**
* DateTimeFormatter :格式化時(shí)間/日期
*/
@Test
public void test6() {
// DateTimeFormatter dateTimeFormat=DateTimeFormatter.ISO_DATE;
// DateTimeFormatter dateTimeFormat=DateTimeFormatter.ISO_LOCAL_TIME;
// DateTimeFormatter dateTimeFormat=DateTimeFormatter.ISO_TIME;
DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
String format = dateTimeFormat.format(now);
System.out.println("format = " + format);
System.out.println("_________________________");
LocalDateTime parse = LocalDateTime.parse(format, dateTimeFormat);
System.out.println(parse);
}
/**
* ZonedDate ,ZonedTime ,ZonedDateTime
*/
@Test
public void test7() {
Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
availableZoneIds.forEach(System.out::println);
}
/**
*
*/
@Test
public void test8() {
LocalDateTime now = LocalDateTime.now(ZoneId.of("Pacific/Yap"));
System.out.println("now = " + now);
LocalDateTime now1 = LocalDateTime.now(ZoneId.of("Pacific/Yap"));
ZonedDateTime zonedDateTime = now1.atZone(ZoneId.of("Pacific/Yap"));
ZonedDateTime zonedDateTime1 = now1.atZone(ZoneId.of("Asia/Shanghai"));
System.out.println(zonedDateTime1);
}
}
SimpleDateFormatTest
package com.www.java8.data;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;
/**
* SimpleDateFormat 存在線程安全問(wèn)題
* <p>
*
* @author Www
* <p>
* 郵箱: 483223455@qq.com
* <p>
* 創(chuàng)建時(shí)間: 2022/8/13 16:26 星期六
* <p>
*/
public class SimpleDateFormatTest {
/**
* 方法入口
*
* @param args 參數(shù)
*/
public static void main(String[] args) throws ExecutionException, InterruptedException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Callable<Date> callable = new Callable<Date>() {
@Override
public Date call() throws Exception {
// return simpleDateFormat.parse("2021-9-9");
return DateFormatThreadLocal.convert("2021-9-9");
}
};
ExecutorService pool = Executors.newFixedThreadPool(10);
List<Future<Date>> results = new ArrayList<>();
for (int i = 0; i < 10; i++) {
results.add(pool.submit(callable));
}
for (Future<Date> result : results) {
System.out.println(result.get());
}
pool.shutdown();
}
}