建設(shè)銀行的網(wǎng)站是多少網(wǎng)絡(luò)營銷專業(yè)是學(xué)什么的
文章目錄
- Java舊時(shí)間類關(guān)系圖
- GMT、時(shí)間戳、統(tǒng)一標(biāo)準(zhǔn)時(shí)間、時(shí)區(qū)
- Java時(shí)間類
- 創(chuàng)建時(shí)間類示例
- java.text.DateFormat時(shí)間格式轉(zhuǎn)換
- java.util.Calendar
- 總結(jié)Java時(shí)間類
- Java8新時(shí)間類
- Instant
- Clock
- LocalDate
- LocalTime
- LocalDateTime
- 時(shí)區(qū)篇
- java.time.ZoneId
- java.time.ZoneOffset
- java.time.OffsetDateTime
- java.time.ZonedDateTime
- 時(shí)間間隔
- java.time.Duration(時(shí)間值)
- java.time.Period(日期值)
- TemporalAdjuster 矯正器
參考文章:Java時(shí)間類匯總
Java舊時(shí)間類關(guān)系圖
GMT、時(shí)間戳、統(tǒng)一標(biāo)準(zhǔn)時(shí)間、時(shí)區(qū)
- GMT:格林尼治標(biāo)準(zhǔn)時(shí)間,是計(jì)算機(jī)中時(shí)間原點(diǎn):1970年1月1日 00:00:00
- 時(shí)間戳:自1970年1月1日(00:00:00 GMT)至當(dāng)前時(shí)間的總秒數(shù)
- UTC:統(tǒng)一的標(biāo)準(zhǔn)時(shí)間
- 時(shí)區(qū):CST可視為中國、美國、澳大利亞或古巴的標(biāo)準(zhǔn)時(shí)間
美國:Central Standard Time UT-6:00
澳大利亞:Central Standard Time UT+9:30
中國:China Standard Time UT+8:00
古巴:Cuba Standard Time UT-4:00
Java時(shí)間類
創(chuàng)建時(shí)間類示例
public class JavaDateTest {public static void main(String[] args) {//public Date()構(gòu)造器//public Date(long date)構(gòu)造器java.util.Date utilDate1 = new java.util.Date();java.util.Date utilDate2 = new java.util.Date(System.currentTimeMillis());//public Date(long date)構(gòu)造器java.sql.Date sqlDate1 = new java.sql.Date(System.currentTimeMillis());//public Time(long date)構(gòu)造器java.sql.Date time = new java.sql.Time(System.currentTimeMillis());//public Timestamp(long date)構(gòu)造器java.sql.Timestamp timestamp = new java.sql.Timestamp(System.currentTimeMillis());System.out.println(utilDate1); // Fri Feb 11 13:00:14 CST 2022 System.out.println(utilDate2); // Fri Feb 11 13:00:14 CST 2022System.out.println(sqlDate2); // 2022-02-11System.out.println(time); // 17:53:45System.out.println(timestamp); //2022-02-11 16:56:00.171}
}
java.text.DateFormat時(shí)間格式轉(zhuǎn)換
1. 該類方法如下
public final String format(Date date):將日期格式化字符串
public Date parse(String source):將字符串轉(zhuǎn)為日期
public void applyPattern(String pattern):設(shè)置指定格式化字符串
public SimpleDateFormat(String pattern):設(shè)置指定格式化的SimpleDateFormat對(duì)象
2. 示例
public class JavaDateTest {public static void main(String[] args) throws ParseException {//默認(rèn)實(shí)例化SimpleDateFormat sdf1 = new SimpleDateFormat();String format1 = sdf1.format(new Date()); //將日期格式化字符串System.out.println(format1); // 2021/12/18 下午6:19Date parse1 = sdf1.parse("2021/11/15 下午3:41"); //將字符串轉(zhuǎn)為日期System.out.println(parse1); // Mon Nov 15 15:41:00 CST 2021// 帶參數(shù)實(shí)例化SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String format2 = sdf2.format(date); // 將日期格式化字符串System.out.println(format2); // 2021-11-15 15:41:00Date parse2 = sdf2.parse("2021-11-15 16:11:27"); //將字符串轉(zhuǎn)為日期System.out.println(parse2); // Mon Nov 15 16:11:27 CST 2021}
}
3. SimpleDateFormat正確使用
方法一:在需要執(zhí)行格式化的地方都新建SimpleDateFormat實(shí)例,使用局部變量來存放SimpleDateFormat實(shí)例。這種方法可能會(huì)導(dǎo)致短期內(nèi)創(chuàng)建大量的SimpleDateFormat實(shí)例,如解析一個(gè)excel表格里的字符串日期。同一個(gè)線程內(nèi)的所有SimpleDateFormat都不同
public static String formatDate(Date date) {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");return sdf.format(date);
}
方法二:為了避免創(chuàng)建大量的SimpleDateFormat實(shí)例,往往會(huì)考慮把SimpleDateFormat實(shí)例設(shè)為靜態(tài)成員變量,共享SimpleDateFormat對(duì)象。這種情況下就得對(duì)SimpleDateFormat添加同步。這種方法的缺點(diǎn)也很明顯,就是在高并發(fā)的環(huán)境下會(huì)導(dǎo)致解析被阻塞。只有一個(gè)SimpleDateFormat,所有用戶都使用這個(gè)
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static String formatDate(Date date) {synchronized (sdf) {return sdf.format(date);}
}
方法三:要在高并發(fā)環(huán)境下能有比較好的體驗(yàn),可以使用ThreadLocal來限制SimpleDateFormat只能在線程內(nèi)共享,這樣就避免了多線程導(dǎo)致的線程安全問題。
private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() {@Overrideprotected DateFormat initialValue() {return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");}
};
public static String formatDate(Date date) {return threadLocal.get().format(date);
}
java.util.Calendar
Calendar的常用屬性
import java.util.Calendar;
import java.util.GregorianCalendar;public class JavaDateTest {public static void main(String[] args) {Calendar gregorianCalendar = new GregorianCalendar(); //創(chuàng)建其子類的實(shí)例化Calendar calendar = Calendar.getInstance(); //調(diào)用其靜態(tài)方法getInstance實(shí)例化// 獲得年份:2022System.out.println("現(xiàn)在是:" + calendar.get(Calendar.YEAR) + "年");// 獲得月份:2System.out.println("現(xiàn)在是:" + (calendar.get(Calendar.MONTH)+1) + "月");//獲得日期(本月的第幾天):13System.out.println("現(xiàn)在是:" + calendar.get(Calendar.DATE) + "號(hào)");System.out.println("現(xiàn)在是:" + calendar.get(Calendar.DAY_OF_MONTH) + "號(hào)");// 獲得這是今年的第幾天:44System.out.println("現(xiàn)在是今年第" + calendar.get(Calendar.DAY_OF_YEAR) + "天");// 獲得今天周幾:0(星期天天)System.out.println("現(xiàn)在是星期:" + (calendar.get(Calendar.DAY_OF_WEEK)-1) );// 獲得今天是這個(gè)月的第幾周:2System.out.println("現(xiàn)在是第:" + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH) + "周" );// 12小時(shí)制的時(shí)間:9System.out.println("現(xiàn)在是:" + calendar.get(Calendar.HOUR) + "點(diǎn)");// 24小時(shí)制的時(shí)間:21System.out.println("現(xiàn)在是:" + calendar.get(Calendar.HOUR_OF_DAY) + "點(diǎn)");// 分鐘數(shù):30System.out.println("現(xiàn)在是:" + calendar.get(Calendar.MINUTE) + "分");// 秒數(shù):21System.out.println("現(xiàn)在是:" + calendar.get(Calendar.SECOND) + "秒");// 毫秒:338System.out.println("現(xiàn)在是:" + calendar.get(Calendar.MILLISECOND) + "毫秒");// 設(shè)置當(dāng)前時(shí)間為本年度的第10天calendar.set(Calendar.DAY_OF_YEAR,10);// 再次調(diào)用get()方法后返回的是更改后的值System.out.println(calendar.get(Calendar.DAY_OF_YEAR)); // 10// 給當(dāng)前日期上加上本年度的3天(現(xiàn)在是本年度的第10天)calendar.add(Calendar.DAY_OF_YEAR,3);System.out.println(calendar.get(Calendar.DAY_OF_YEAR)); // 13// getTime()方法實(shí)現(xiàn) calendar 類 -> Date類// 得到的Date類型變量是Calendar對(duì)象經(jīng)過修改后的時(shí)間java.util.Date time = calendar.getTime();System.out.println(time); // Thu Jan 13 21:12:50 CST 2022//setTime()方法實(shí)現(xiàn) Date類 -> Calendar 類calendar.setTime(new java.util.Date());// 通過該Calendar實(shí)例對(duì)象調(diào)用get方法得知傳入Date類型變量是一年中的第幾天等信息System.out.println(calendar.get(Calendar.DAY_OF_MONTH)); // 13}
}
總結(jié)Java時(shí)間類
- 創(chuàng)建時(shí)間對(duì)象
- new java.util.Date(System.currentTimeMillis())、new java.util.Date()
- new java.sql.Date(System.currentTimeMillis())
- new java.sql.Time(System.currentTimeMillis())
- new java.sql.Timestamp(System.currentTimeMillis())
- new GregorianCalendar();
- Calender.getInstance();
- 對(duì)象規(guī)范化
SimpleDateFormat sdf1 = new SimpleDateFormat();
String format1 = sdf1.format(new Date()); //將日期格式化字符串
System.out.println(format1); // 2021/12/18 下午6:19
Date parse1 = sdf1.parse(“2021/11/15 下午3:41”); //將字符串轉(zhuǎn)為日期
System.out.println(parse1); // Mon Nov 15 15:41:00 CST 2021
Java8新時(shí)間類
Instant
- public static Instant now():返回時(shí)間戳
- public static Instant ofEpochMilli(long epochMilli):通過給定毫秒數(shù),獲取Instance實(shí)例
- public static Instant ofEpochSecond(long epochSecond):通過給定秒數(shù),獲取Instance實(shí)例
- public static Instant parse(final CharSequence text):字符串轉(zhuǎn)換成Instance實(shí)例
- public OffsetDateTime atOffset(ZoneOffset offset):根據(jù)時(shí)區(qū)修正偏移量,北京時(shí)間應(yīng)該+8
- public ZonedDateTime atZone(ZoneId zone):獲取系統(tǒng)默認(rèn)時(shí)區(qū)時(shí)間
- public long getEpochSecond():獲取從1970-01-01 00:00:00到當(dāng)前時(shí)間的秒值
- public long toEpochMilli():獲取從1970-01-01 00:00:00到當(dāng)前時(shí)間的毫秒值
- public int getNano():把獲取到的當(dāng)前時(shí)間的秒數(shù)換算成納秒
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.Date;public class JavaDateTest {public static void main(String[] args) {/*** 實(shí)例方式一:通過靜態(tài)方法now(),獲得UTC(本初子午線)的此刻瞬時(shí)時(shí)間的實(shí)例對(duì)象* 輸出內(nèi)容(默認(rèn)時(shí)間比北京時(shí)間相差8小時(shí)):2022-02-16T07:22:12.266171900Z(Z表示本初子午線)* 注:不建議使用Instant查看當(dāng)前時(shí)間點(diǎn)*/Instant instant1 = Instant.now();System.out.println(instant1); // 2022-02-16T07:22:12.266Z/*** 實(shí)例化方式二:通過給定毫秒數(shù)或秒數(shù),獲取Instant實(shí)例*/System.out.println(Instant.ofEpochMilli(Clock.systemDefaultZone().millis())); // 2022-02-16T07:22:12.266ZSystem.out.println(Instant.ofEpochMilli(Clock.systemUTC().millis())); // 2022-02-16T07:22:12.266ZSystem.out.println(Instant.ofEpochMilli(new Date().getTime())); // 2022-02-16T07:22:12.266ZSystem.out.println(Instant.ofEpochMilli(System.currentTimeMillis())); // 2022-02-16T07:22:12.266ZSystem.out.println(Instant.ofEpochSecond(System.currentTimeMillis() / 1000)); // 2022-02-16T07:22:12Z/*** 實(shí)例化方式三:將字符串轉(zhuǎn)換成Instant*/System.out.println(Instant.parse("2022-02-16T07:22:12.266Z")); // 2022-02-16T07:22:12.266Z/*** long getEpochSecond():獲取當(dāng)前時(shí)間戳的秒數(shù):* long toEpochMilli():獲取當(dāng)前時(shí)間戳的毫秒:* int getNano():獲取當(dāng)前時(shí)間點(diǎn)(拋開整數(shù)秒不算)的納秒數(shù)* 如: 12345.12秒,拋開整數(shù)秒不算,則為0.12秒,那么instant.getNano()的結(jié)果為 0.12 * 1000_000_000 = 120_000_000*/System.out.println("秒數(shù) -> " + Instant.now().getEpochSecond()); // 秒數(shù) -> 1644997084System.out.println("毫秒數(shù) -> " + Instant.now().toEpochMilli()); // 毫秒數(shù) -> 1644997084046System.out.println("納秒數(shù) -> " + Instant.now().getNano()); // 納秒數(shù) -> 46179600/*** Instant 與 時(shí)間偏移量 的相互轉(zhuǎn)換, 注:從1970-01-01 00:00:00開始計(jì)算偏移*/System.out.println(Instant.now()); // 2022-02-16T07:44:36.084408900Z// 對(duì)時(shí)間進(jìn)行時(shí)區(qū)偏移修正,北京時(shí)間應(yīng)+8,輸出內(nèi)容可以發(fā)現(xiàn)->(Z變?yōu)?#43;8:00)System.out.println(Instant.now().atOffset(ZoneOffset.ofHours(8))); // 2022-02-16T15:44:36.084408900+08:00// 設(shè)置時(shí)區(qū)后,顯示時(shí)間為北京時(shí)間了->(可以發(fā)現(xiàn)后面帶上了時(shí)區(qū))System.out.println(Instant.now().atZone(ZoneId.systemDefault())); // 2022-02-16T15:44:36.084408900+08:00[Asia/Shanghai]/*** Instant的時(shí)間加、減:* 由于北京時(shí)間比UTC時(shí)間晚8小時(shí),所以我們需要得出北京的瞬時(shí)時(shí)間,需要加8小時(shí)*/Instant instant3 = Instant.now().plus(8, ChronoUnit.HOURS);// 原(北京瞬時(shí))instant -> 2022-02-16T15:22:12.266653300ZSystem.out.println("原(北京瞬時(shí))instant -> " + instant3);Instant plusRes = instant3.plus(1, ChronoUnit.HOURS); // + 1 小時(shí)// 原(北京瞬時(shí))instant + 1小時(shí),結(jié)果是 -> 2022-02-16T16:22:12.266653300ZSystem.out.println("原(北京瞬時(shí))instant + 1小時(shí),結(jié)果是 -> " + plusRes);Instant minusRes = instant3.minus(2, ChronoUnit.HOURS); // - 2 小時(shí)// 原(北京瞬時(shí))instant - 2小時(shí),結(jié)果是 -> 2022-02-16T13:22:12.266653300ZSystem.out.println("原(北京瞬時(shí))instant - 2小時(shí),結(jié)果是 -> " + minusRes);/*** 判斷兩個(gè)Instant之間誰早誰晚*/// 將Clock轉(zhuǎn)換成InstantInstant instantOne = Instant.now(Clock.systemDefaultZone());// 對(duì)時(shí)間進(jìn)行時(shí)區(qū)偏移修正,北京時(shí)間應(yīng)+8Instant instantTwo = instantOne.plus(8, ChronoUnit.HOURS);boolean isAfterResult = instantOne.isAfter(instantTwo);// 瞬時(shí)時(shí)間點(diǎn)instantOne晚于instantTwo ? --- falseSystem.out.println("瞬時(shí)時(shí)間點(diǎn)instantOne晚于instantTwo ? --- " + isAfterResult);// 瞬時(shí)時(shí)間點(diǎn)instantOne早于instantTwo ? --- trueboolean isBeforeResult = instantOne.isBefore(instantTwo);System.out.println("瞬時(shí)時(shí)間點(diǎn)instantOne早于instantTwo ? --- " + isBeforeResult);}
}
Clock
import java.time.Clock;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;public class JavaDateTest {public static void main(String[] args) {// 系統(tǒng)時(shí)區(qū)默認(rèn)時(shí)間, 通過clock.instant()方法獲取當(dāng)前時(shí)刻Clock clock = Clock.systemDefaultZone();System.out.println(clock); // SystemClock[Asia/Shanghai]System.out.println(clock.getZone()); // Asia/ShanghaiSystem.out.println("當(dāng)前時(shí)刻為:" + clock.instant()); // 當(dāng)前時(shí)刻為:2022-02-18T08:25:12.954071700Z// 世界協(xié)調(diào)時(shí)UTCClock clockUTC = Clock.systemUTC();System.out.println(clockUTC); // SystemClock[Z]System.out.println(clockUTC.getZone()); // ZSystem.out.println("當(dāng)前時(shí)刻為:" + clockUTC.instant()); // 當(dāng)前時(shí)刻為:2022-02-18T08:25:12.973084700Z// 獲取Clock對(duì)應(yīng)的毫秒數(shù),與System.currentTimeMillis()輸出相同System.out.println(Clock.systemDefaultZone().millis()); // 1645172712973System.out.println(Clock.systemUTC().millis()); // 1645172712973System.out.println(System.currentTimeMillis()); // 1645172712973// 在clock基礎(chǔ)上增加6000秒,返回新的ClockClock clockSet = Clock.offset(clockUTC, Duration.ofSeconds(6000));System.out.println(clockSet); // OffsetClock[SystemClock[Z],PT1H40M]System.out.println(clockSet.getZone()); // ZSystem.out.println("當(dāng)前時(shí)刻為:" + clockSet.instant()); // 當(dāng)前時(shí)刻為:2022-02-18T10:05:12.974077200Z// 紐約時(shí)間Clock clockNewYork = Clock.system(ZoneId.of("America/New_York"));// Current DateTime with NewYork clock: 2022-02-18T03:25:12.975086200System.out.println("Current DateTime with NewYork clock: " + LocalDateTime.now(clockNewYork));System.out.println(clockNewYork.millis()); // 1645172712977// 返回具有不同時(shí)區(qū)的此時(shí)鐘的副本, withZone(ZoneId zoneId)Clock systemDefaultZone = Clock.systemDefaultZone();Clock withZone = systemDefaultZone.withZone(ZoneId.of("America/New_York"));System.out.println(systemDefaultZone); // SystemClock[Asia/Shanghai]System.out.println(withZone); // SystemClock[America/New_York]/*** Clock tick(Clock baseClock, Duration tickDuration):此方法獲得一個(gè)時(shí)鐘,該時(shí)鐘返回從指定時(shí)鐘被截?cái)嗟街付ǔ掷m(xù)時(shí)間的最接近值的瞬間* Clock tickMinutes(ZoneId zone):此方法獲得一個(gè)時(shí)鐘,該時(shí)鐘使用最佳的可用系統(tǒng)時(shí)鐘返回整分鐘的當(dāng)前即時(shí)滴答* Clock tickSeconds(ZoneId zone) 此方法獲得一個(gè)時(shí)鐘,該時(shí)鐘使用最佳可用系統(tǒng)時(shí)鐘返回整秒的當(dāng)前即時(shí)滴答。*/Clock clock1 = Clock.systemDefaultZone();Clock clock2 = Clock.tick(clock1, Duration.ofDays(1));System.out.println("Clock1 : " + clock1.instant()); // Clock1 : 2022-02-18T08:25:12.977085300ZSystem.out.println("Clock2 : " + clock2.instant()); // Clock2 : 2022-02-18T00:00:00ZClock clock3 = Clock.systemDefaultZone();Clock clock4 = Clock.tickMinutes(ZoneId.systemDefault());System.out.println("Clock3 : " + clock3.instant()); // Clock3 : 2022-02-18T08:25:12.977085300ZSystem.out.println("Clock4 : " + clock4.instant()); // Clock4 : 2022-02-18T08:25:00ZClock clock5 = Clock.systemDefaultZone();Clock clock6 = Clock.tickSeconds(ZoneId.systemDefault());System.out.println("Clock5 : " + clock5.instant()); // Clock5 : 2022-02-18T08:25:12.978077500ZSystem.out.println("Clock6 : " + clock6.instant()); // Clock6 : 2022-02-18T08:25:12Z}
}
LocalDate
import java.time.LocalDate;public class JavaDateTest {public static void main(String[] args) {/*** 常用的兩種實(shí)例化方式:* 1.通過靜態(tài)方法, 獲取系統(tǒng)的當(dāng)前時(shí)間:LocalDate.now()* 2.通過靜態(tài)方法, 獲取自定義指定時(shí)間:LocalDate.of(2022, 02, 28)*/LocalDate today = LocalDate.now(); // 獲取當(dāng)前日期(年/月/日) 2020-6-14 周天LocalDate of = LocalDate.of(2022, 02, 28);/*** 常用的getXxx()系列操作,獲得日期:* int getYear() 獲取當(dāng)前?期的年份* Month getMonth() 獲取當(dāng)前?期的?份對(duì)象(返回一個(gè) Month 枚舉值)* int getMonthValue() 獲取當(dāng)前?期是第??(1-12)* int getDayOfMonth() 表示該對(duì)象表示的?期是這個(gè)?第?天(1-31)* DayOfWeek getDayOfWeek() 表示該對(duì)象表示的?期是星期?(返回一個(gè) DayOfWeek枚舉值)* int getDayOfYear() 表示該對(duì)象表示的?期是今年第?天(1-366)*/System.out.println("今天的?期:" + today); // 今天的?期:2020-06-14System.out.println("指定的?期:" + of); // 指定的?期:2022-02-28System.out.println("現(xiàn)在是哪年:" + today.getYear()); // 現(xiàn)在是哪年:2020System.out.println("現(xiàn)在是哪?(英文):" + today.getMonth()); // 現(xiàn)在是哪?(英文):JUNESystem.out.println("現(xiàn)在是哪?(數(shù)字):" + today.getMonthValue()); // 現(xiàn)在是哪?(數(shù)字):6System.out.println("現(xiàn)在是?號(hào):" + today.getDayOfMonth()); // 現(xiàn)在是?號(hào):14System.out.println("現(xiàn)在是周?:" + today.getDayOfWeek()); // 現(xiàn)在是周?:SUNDAYSystem.out.println("現(xiàn)在是今年的第幾天:" + today.getDayOfYear()); // 現(xiàn)在是今年的第幾天:166/*** 常用的setXxx()系列操作,設(shè)置日期:* LocalDate withYear(int year) 修改當(dāng)前對(duì)象的年份* LocalDate withMonth(int month) 修改當(dāng)前對(duì)象的?份* LocalDate withDayOfMonth(int dayOfMonth) 修改當(dāng)前對(duì)象在當(dāng)?的?期* LocalDate withDayOfYear(int dayOfYear) 修改當(dāng)前對(duì)象在當(dāng)年的?期*/LocalDate withLocalDate = LocalDate.of(2022, 01, 01);System.out.println("常用的setXxx()系列操作:" + withLocalDate); // 此刻時(shí)間:2022-01-01(用作對(duì)比參考)System.out.println(withLocalDate.withYear(2030));// 2030-01-01System.out.println(withLocalDate.withMonth(2)); // 2022-02-01System.out.println(withLocalDate.withDayOfMonth(8)); // 2022-01-08System.out.println(withLocalDate.withDayOfYear(10)); // 2022-01-10/*** 常用的plusXxx()系列操作,增加時(shí)間的方法:* LocalDate plusYears(long yearsToAdd) 增加指定年份數(shù)* LocalDate plusMonths(long monthsToAdd) 增加指定?份數(shù)* LocalDate plusDays(long daysToAdd) 增加指定天數(shù)* LocalDate plusWeeks(long weeksToAdd) 增加指定周數(shù)*/LocalDate plusLocalDate = LocalDate.of(2022, 01, 01);System.out.println("常用的plusXxx()系列操作:" + plusLocalDate); // 此刻時(shí)間:2022-01-01(用作對(duì)比參考)System.out.println(plusLocalDate.plusYears(1)); // 2023-01-01System.out.println(plusLocalDate.plusMonths(1)); // 2022-02-01System.out.println(plusLocalDate.plusWeeks(1)); // 2022-01-08System.out.println(plusLocalDate.plusDays(6)); // 2022-01-07/*** 常用的minusXxx()系列操作,減少時(shí)間的方法:* LocalDate minusYears(long yearsToSubtract) 減去指定年數(shù)* LocalDate minusMonths(long monthsToSubtract) 減去注定?數(shù)* LocalDate minusDays(long daysToSubtract) 減去指定天數(shù)* LocalDate minusWeeks(long weeksToSubtract) 減去指定周數(shù)*/LocalDate minusLocalDate = LocalDate.of(2022, 01, 01);System.out.println("常用的minusXxx()系列操作:" + minusLocalDate); // 此刻時(shí)間:2022-01-01(用作對(duì)比參考)System.out.println(minusLocalDate.minusYears(5)); // 2017-01-01System.out.println(minusLocalDate.minusMonths(60)); // 2017-01-01System.out.println(minusLocalDate.minusWeeks(260)); // 2017-01-07System.out.println(minusLocalDate.minusDays(1826)); // 2017-01-01/*** 常用日期對(duì)比方法:* int compareTo(ChronoLocalDate other) ?較當(dāng)前對(duì)象和other對(duì)象在時(shí)間上的??,返回值如果為正,則當(dāng)前對(duì)象時(shí)間較晚* boolean isBefore(ChronoLocalDate other) ?較當(dāng)前對(duì)象?期是否在other對(duì)象?期之前* boolean isAfter(ChronoLocalDate other) ?較當(dāng)前對(duì)象?期是否在other對(duì)象?期之后* boolean isEqual(ChronoLocalDate other) ?較兩個(gè)?期對(duì)象是否相等* boolean isLeapYear() 判斷是否是閏年(注意是LocalDate類 和 LocalDateTime類特有的方法)*/LocalDate localDateOne = LocalDate.of(2022, 01, 01);LocalDate localDateTwo = LocalDate.of(2000, 01, 01);System.out.println("compareTo: " + localDateOne.compareTo(localDateTwo)); // compareTo: 22System.out.println("isBefore: " + localDateOne.isBefore(localDateTwo)); // isBefore: falseSystem.out.println("isAfter: " + localDateOne.isAfter(localDateTwo)); // isAfter: trueSystem.out.println("isEqual: " + localDateOne.isEqual(localDateTwo)); // isEqual: falseSystem.out.println("isLeapYear: " + localDateTwo.isLeapYear()); // isLeapYear: true}
}
LocalTime
import java.time.LocalTime;public class JavaDateTest {public static void main(String[] args) {/*** 常用的兩種實(shí)例化方式:* 1.通過靜態(tài)方法, 獲取系統(tǒng)的當(dāng)前時(shí)間:LocalTime.now()* 2.通過靜態(tài)方法, 獲取自定義指定時(shí)間:LocalTime.of(21, 30, 59, 11001);*/LocalTime today = LocalTime.now();LocalTime of = LocalTime.of(21, 30, 59, 11001);System.out.println("指定的時(shí)間:" + of); // 指定的時(shí)間:18:24:31.761102500/*** 常用的getXxx()系列操作,獲得日期:* int getHour() 獲取當(dāng)前時(shí)間小時(shí)數(shù)* int getMinute() 獲取當(dāng)前時(shí)間分鐘數(shù)* int getSecond() 獲取當(dāng)前時(shí)間秒值* int getNano() 把獲取到的當(dāng)前時(shí)間的秒數(shù)換算成納秒*/System.out.println("今天的時(shí)間:" + today); // 今天的時(shí)間:18:24:31.761102500System.out.println("現(xiàn)在是幾時(shí):" + today.getHour()); // 現(xiàn)在是幾時(shí):18System.out.println("現(xiàn)在是幾分:" + today.getMinute()); // 現(xiàn)在是幾分:24System.out.println("現(xiàn)在是幾秒:" + today.getSecond()); // 現(xiàn)在是幾秒:31System.out.println("現(xiàn)在是?納秒:" + today.getNano()); // 現(xiàn)在是?納秒:761102500/*** 常用的setXxx()系列操作,設(shè)置日期:* LocalTime withHour(int hour) 修改當(dāng)前對(duì)象的小時(shí)數(shù)* LocalTime withMinute(int minute) 修改當(dāng)前對(duì)象的分鐘數(shù)* LocalTime withSecond(int second) 修改當(dāng)前對(duì)象在當(dāng)?的秒數(shù)* LocalTime withNano(int nanoOfSecond) 修改當(dāng)前對(duì)象在當(dāng)年的納秒數(shù)*/LocalTime withLocalTime = LocalTime.of(13, 8, 20, 123456789);System.out.println("常用的setXxx()系列操作:" + withLocalTime); // 此刻時(shí)間:13:08:20.123456789(用作對(duì)比參考)System.out.println(withLocalTime.withHour(5)); // 05:08:20.123456789System.out.println(withLocalTime.withMinute(10)); // 13:10:20.123456789System.out.println(withLocalTime.withSecond(8)); // 13:08:08.123456789System.out.println(withLocalTime.withNano(100000001)); // 13:08:20.100000001/*** 常用的plusXxx()系列操作,增加時(shí)間的方法:* LocalTime plusHours(long hoursToAdd) 增加指定小時(shí)* LocalTime plusMinutes(long minutesToAdd) 增加指定分鐘* LocalTime plusSeconds(long secondstoAdd) 增加指定秒* LocalTime plusNanos(long nanosToAdd) 增加指定納秒*/LocalTime plusLocalTime = LocalTime.of(13, 8, 20, 123456789);System.out.println("常用的plusXxx()系列操作:" + plusLocalTime); // 此刻時(shí)間:13:08:20.123456789(用作對(duì)比參考)System.out.println(plusLocalTime.plusHours(1)); // 14:08:20.123456789System.out.println(plusLocalTime.plusMinutes(1)); // 13:09:20.123456789System.out.println(plusLocalTime.plusSeconds(1)); // 13:08:21.123456789System.out.println(plusLocalTime.plusNanos(6)); // 13:08:20.123456795/*** 常用的minusXxx()系列操作,減少時(shí)間的方法:* LocalTime minusHours(long hoursToSubtract) 減去指定年數(shù)* LocalTime minusMinutes(long minutesToSubtract) 減去注定?數(shù)* LocalTime minusSeconds(long secondsToSubtract) 減去指定天數(shù)* LocalTime minusNanos(long nanosToSubtract) 減去指定周數(shù)*/LocalTime minusLocalTime = LocalTime.of(13, 8, 20, 123456789);System.out.println("常用的minusXxx()系列操作:" + minusLocalTime); // 此刻時(shí)間:13:08:20.123456789(用作對(duì)比參考)System.out.println(minusLocalTime.minusHours(1)); // 12:08:20.123456789System.out.println(minusLocalTime.minusMinutes(60)); // 12:08:20.123456789System.out.println(minusLocalTime.minusSeconds(3600)); // 12:08:20.123456789System.out.println(minusLocalTime.minusNanos(9)); // 13:08:20.123456780/*** 常用日期對(duì)比方法:* int compareTo(LocalTime other) ?較當(dāng)前對(duì)象和other對(duì)象在時(shí)間上的??,返回值如果為正,則當(dāng)前對(duì)象時(shí)間較晚* boolean isBefore(LocalTime other) ?較當(dāng)前對(duì)象時(shí)間是否在other對(duì)象時(shí)間之前* boolean isAfter(LocalTime other) ?較當(dāng)前對(duì)象時(shí)間是否在other對(duì)象時(shí)間之后*/LocalTime localTimeOne = LocalTime.of(13, 8, 20, 123456789);LocalTime localTimeTwo = LocalTime.of(10, 8, 20, 123456789);System.out.println("compareTo: " + localTimeOne.compareTo(localTimeTwo)); // compareTo: 1System.out.println("isBefore: " + localTimeOne.isBefore(localTimeTwo)); // isBefore: falseSystem.out.println("isAfter: " + localTimeOne.isAfter(localTimeTwo)); // isAfter: true}
}
LocalDateTime
import java.time.*;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;public class JavaDateTest {public static void main(String[] args) {/*** 常用的兩種實(shí)例化方式:* 1.通過靜態(tài)方法, 獲取系統(tǒng)的當(dāng)前時(shí)間:LocalTime.now()* 2.通過靜態(tài)方法, 獲取自定義指定時(shí)間:* 1.LocalDateTime.of(LocalDate.now(), LocalTime.now())* 2.LocalDateTime.of(2020,02,8,21, 30, 59, 11001)* 3.通過LocalDateTime轉(zhuǎn)換LocalDate、LocalTime*/LocalDateTime today = LocalDateTime.now();LocalDateTime of1 = LocalDateTime.of(LocalDate.now(), LocalTime.now());LocalDateTime of2 = LocalDateTime.of(2020,02,8,21, 30, 59, 11001);/*** 轉(zhuǎn)換的方法:* LocalDate toLocalDate():將LocalDateTime轉(zhuǎn)換為相應(yīng)的LocalDate對(duì)象* LocalTime toLocalTime():將LocalDateTime轉(zhuǎn)換為相應(yīng)的LocalTime對(duì)象*/LocalDate localDate = today.toLocalDate();LocalTime localTime = today.toLocalTime();/*** 常用的getXxx()系列操作,獲得日期:* int getYear() 獲取當(dāng)前日期的年份* Month getMonth() 獲取當(dāng)前日期的月份對(duì)象(返回一個(gè)Month枚舉值)* int getMonthValue() 獲取當(dāng)前日期是第幾月(1-12)* int getDayOfMonth() 表示該對(duì)象表示的?期是這個(gè)?第?天(1-31)* DayOfWeek getDayOfWeek() 表示該對(duì)象表示的日期是星期幾(返回一個(gè)DayOfWeek枚舉值)* int getDayOfYear() 表示該對(duì)象表示的日期是今年第幾天(1-366)* int getHour() 獲取當(dāng)前時(shí)間小時(shí)數(shù)* int getMinute() 獲取當(dāng)前時(shí)間分鐘數(shù)* int getSecond() 獲取當(dāng)前時(shí)間秒值* int getNano() 把獲取到的當(dāng)前時(shí)間的秒數(shù)換算成納秒* int get(TemporalField field) 獲取指定字段的日期時(shí)間,通過ChronoField枚舉類*/System.out.println("今天的時(shí)間:" + today); // 今天的時(shí)間:2022-02-17T19:13:38.682102600System.out.println("現(xiàn)在是哪年:" + today.getYear()); // 現(xiàn)在是哪年:2022System.out.println("現(xiàn)在是哪?(英文):" + today.getMonth()); // 現(xiàn)在是哪?(英文):FEBRUARYSystem.out.println("現(xiàn)在是哪?(數(shù)字):" + today.getMonthValue()); // 現(xiàn)在是哪?(數(shù)字):2System.out.println("現(xiàn)在是?號(hào):" + today.getDayOfMonth()); // 現(xiàn)在是?號(hào):17System.out.println("現(xiàn)在是周?:" + today.getDayOfWeek()); // 現(xiàn)在是周?:THURSDAYSystem.out.println("現(xiàn)在是該年的第幾天:" + today.getDayOfYear()); // 現(xiàn)在是該年的第幾天:48System.out.println("現(xiàn)在是幾時(shí):" + today.getHour()); // 現(xiàn)在是幾時(shí):19System.out.println("現(xiàn)在是幾分:" + today.getMinute()); // 現(xiàn)在是幾分:13System.out.println("現(xiàn)在是幾秒:" + today.getSecond()); // 現(xiàn)在是幾秒:38System.out.println("現(xiàn)在是?納秒:" + today.getNano()); // 現(xiàn)在是?納秒:682102600System.out.println("現(xiàn)在是?號(hào):" + today.get(ChronoField.DAY_OF_MONTH)); // 現(xiàn)在是?號(hào):19/*** 常用的setXxx()系列操作,設(shè)置日期:* LocalDateTime withYear(int year) 指定對(duì)象的年份* LocalDateTime withMonth(int month) 指定對(duì)象的月份* LocalDateTime withDayOfMonth(int dayOfMonth) 指定對(duì)象在當(dāng)月的日期* LocalDateTime withDayOfYear(int dayOfYear) 指定對(duì)象在當(dāng)年的日期* LocalDateTime withHour(int hour) 指定對(duì)象的小時(shí)數(shù)* LocalDateTime withMinute(int minute) 指定對(duì)象的分鐘數(shù)* LocalDateTime withSecond(int second) 指定對(duì)象在當(dāng)?的秒數(shù)* LocalDateTime withNano(int nanoOfSecond) 指定對(duì)象在當(dāng)年的納秒數(shù)* LocalDateTime with(TemporalField field, long newValue) 指定對(duì)象的日期時(shí)間,通過ChronoField枚舉類*/LocalDateTime withLocalDateTime = LocalDateTime.of(2020,02,8,21, 30, 59, 123456789);System.out.println("常用的setXxx()系列操作:" + withLocalDateTime); // 常用的setXxx()系列操作:2020-02-08T21:30:59.123456789System.out.println(withLocalDateTime.withYear(2030));// 2030-02-08T21:30:59.123456789System.out.println(withLocalDateTime.withMonth(2)); // 2020-02-08T21:30:59.123456789System.out.println(withLocalDateTime.withDayOfMonth(8)); // 2020-02-08T21:30:59.123456789System.out.println(withLocalDateTime.withDayOfYear(10)); // 2020-01-10T21:30:59.123456789System.out.println(withLocalDateTime.withHour(5)); // 2020-02-08T05:30:59.123456789System.out.println(withLocalDateTime.withMinute(10)); // 2020-02-08T21:10:59.123456789System.out.println(withLocalDateTime.withSecond(8)); // 2020-02-08T21:30:08.123456789System.out.println(withLocalDateTime.withNano(100000001)); // 2020-02-08T21:30:59.100000001System.out.println(withLocalDateTime.with(ChronoField.DAY_OF_MONTH, 1)); // 2020-02-01T21:30:59.123456789/*** 常用的plusXxx()系列操作,增加時(shí)間的方法:* LocalDateTime plusYears(long years) 增加指定年份數(shù)* LocalDateTime plusMonths(long months) 增加指定?份數(shù)* LocalDateTime plusDays(long days) 增加指定天數(shù)* LocalDateTime plusWeeks(long weeks) 增加指定周數(shù)* LocalDateTime plusHours(long hours) 增加指定小時(shí)* LocalDateTime plusMinutes(long minutes) 增加指定分鐘* LocalDateTime plusSeconds(long seconds) 增加指定秒* LocalDateTime plusNanos(long nanos) 增加指定納秒* plus(long amountToAdd, TemporalUnit unit) 指定增加的字段的日期時(shí)間*/LocalDateTime plusLocalDateTime = LocalDateTime.of(2020,02,8,21, 30, 59, 123456789);System.out.println("常用的plusXxx()系列操作:" + plusLocalDateTime); // 常用的plusXxx()系列操作:2020-02-08T21:30:59.123456789System.out.println(plusLocalDateTime.plusYears(1)); // 2021-02-08T21:30:59.123456789System.out.println(plusLocalDateTime.plusMonths(1)); // 2020-03-08T21:30:59.123456789System.out.println(plusLocalDateTime.plusDays(6)); // 2020-02-14T21:30:59.123456789System.out.println(plusLocalDateTime.plusWeeks(1)); // 2020-02-15T21:30:59.123456789System.out.println(plusLocalDateTime.plusHours(1)); // 2020-02-08T22:30:59.123456789System.out.println(plusLocalDateTime.plusMinutes(1)); // 2020-02-08T21:31:59.123456789System.out.println(plusLocalDateTime.plusSeconds(1)); // 2020-02-08T21:31:00.123456789System.out.println(plusLocalDateTime.plusNanos(6)); // 2020-02-08T21:30:59.123456795System.out.println(plusLocalDateTime.plus(1, ChronoUnit.DAYS)); // 2020-02-09T21:30:59.123456789/*** 常用的minusXxx()系列操作,減少時(shí)間的方法:* LocalDateTime minusYears(long years) 減去指定年份* LocalDateTime minusMonths(long months) 減去指定月份* LocalDateTime minusDays(long days) 減去指定天數(shù)* LocalDateTime minusWeeks(long weeks) 減去指定周數(shù)* LocalDateTime minusHours(long hours) 減去指定小時(shí)* LocalDateTime minusMinutes(long minutes) 減去指定分鐘* LocalDateTime minusSeconds(long seconds) 減去指定秒* LocalDateTime minusNanos(long nanos) 減去指定納秒* LocalDateTime minus(long amountToSubtract, TemporalUnit unit) 減少指定字段的日期時(shí)間*/LocalDateTime minusLocalDateTime = LocalDateTime.of(2020,02,8,21, 30, 59, 123456789);System.out.println("常用的minusXxx()系列操作:" + minusLocalDateTime); // 常用的minusXxx()系列操作:2020-02-08T21:30:59.123456789System.out.println(minusLocalDateTime.minusYears(5)); // 2015-02-08T21:30:59.123456789System.out.println(minusLocalDateTime.minusMonths(60)); // 2015-02-08T21:30:59.123456789System.out.println(minusLocalDateTime.minusDays(1826)); // 2015-02-08T21:30:59.123456789System.out.println(minusLocalDateTime.minusWeeks(260)); // 2015-02-14T21:30:59.123456789System.out.println(minusLocalDateTime.minusHours(1)); // 2020-02-08T20:30:59.123456789System.out.println(minusLocalDateTime.minusMinutes(60)); // 2020-02-08T20:30:59.123456789System.out.println(minusLocalDateTime.minusSeconds(3600)); // 2020-02-08T20:30:59.123456789System.out.println(minusLocalDateTime.minusNanos(9)); // 2020-02-08T21:30:59.123456780System.out.println(minusLocalDateTime.minus(1, ChronoUnit.HOURS)); // 2020-02-08T20:30:59.123456789/*** 常用日期對(duì)比方法:* int compareTo(localDateTimeOne other) 比較當(dāng)前對(duì)象和other對(duì)象在時(shí)間上的大小,返回值如果為正,則當(dāng)前對(duì)象時(shí)間較晚* boolean isBefore(localDateTimeOne other) 比較當(dāng)前對(duì)象時(shí)間是否在other對(duì)象時(shí)間之前* boolean isAfter(localDateTimeOne other) 比較當(dāng)前對(duì)象時(shí)間是否在other對(duì)象時(shí)間之后* boolean isEqual(ChronoLocalDateTime other) 比較兩個(gè)日期對(duì)象是否相等*/LocalDateTime localDateTimeOne = LocalDateTime.of(2022,02,8,21, 30, 59, 123456789);LocalDateTime localDateTimeTwo = LocalDateTime.of(2020,02,8,21, 30, 59, 123456789);System.out.println("compareTo: " + localDateTimeOne.compareTo(localDateTimeTwo)); // compareTo: 2System.out.println("isBefore: " + localDateTimeOne.isBefore(localDateTimeTwo)); // isBefore: falseSystem.out.println("isAfter: " + localDateTimeOne.isAfter(localDateTimeTwo)); // isAfter: trueSystem.out.println("isEqual: " + localDateTimeOne.isEqual(localDateTimeTwo)); // isEqual: false/*** 從LocalDateTime實(shí)例獲取時(shí)間戳* 從LocalDateTime獲取時(shí)間戳稍微有點(diǎn)麻煩,需先把LocalDateTime實(shí)例轉(zhuǎn)為Instant實(shí)例,再調(diào)用Instant實(shí)例的toEpochMilli方法獲得對(duì)應(yīng)的時(shí)間戳。* 下面示例從本地日期時(shí)間實(shí)例獲取對(duì)應(yīng)的時(shí)間戳*/LocalDateTime now = LocalDateTime.now();Instant instant1 = now.toInstant(ZoneOffset.ofHours(8));System.out.println("timeFromLocal1 = " + instant1.toEpochMilli()); // timeFromLocal1 = 1645272488866/*** 上面獲取代碼基于北京時(shí)間,所以轉(zhuǎn)為Instant實(shí)例時(shí)使用了東八區(qū)。* 倘若在東八區(qū)以外的其他地區(qū)運(yùn)行上述代碼,就無法得到正確的當(dāng)?shù)貢r(shí)間戳,此時(shí)要先設(shè)置當(dāng)?shù)氐哪J(rèn)時(shí)區(qū),再將LocalDateTime實(shí)例轉(zhuǎn)為Instant實(shí)例*/Instant instant2 = now.atZone(ZoneId.systemDefault()).toInstant();System.out.println("timeFromLocal2 = " + instant2.toEpochMilli()); // timeFromLocal2 = 1645272488866/*** 當(dāng)前日期時(shí)間替換成指定的日期時(shí)間, 這里會(huì)用到一個(gè)方法adjustInto()* Temporal adjustInto(Temporal temporal) 將指定的時(shí)間對(duì)象調(diào)整為具有與此對(duì)象相同的日期和時(shí)間* 不常用(該方法不學(xué)也罷)*/// 獲取當(dāng)前時(shí)間LocalDateTime localDateTime = LocalDateTime.now();System.out.println("轉(zhuǎn)換前的時(shí)間:" + localDateTime); // 轉(zhuǎn)換前的時(shí)間:2022-02-19T22:25:20.859059200// 使用adjustInto()方法后LocalDateTime localDateTimeOf = LocalDateTime.of(2020,12,12,12,00,01);localDateTime = (LocalDateTime)localDateTimeOf.adjustInto(localDateTime);System.out.println("轉(zhuǎn)換后的時(shí)間:" + localDateTime); // 轉(zhuǎn)換后的時(shí)間:2020-12-12T12:00:01}
}
時(shí)區(qū)篇
首先介紹:LocalDateTime、OffsetDateTime 和 ZoneDateTime 之間的關(guān)系,且與 ZoneOffset(偏移量)和 ZoneId(時(shí)區(qū)) 的概念。
┌─────────────┐─────────────┐────────────┐────────────┐
│ LocalDate │ LocalTime │ ZoneOffset │ ZoneId │
└─────────────┘─────────────┘────────────┘────────────┘
┌───────────────────────────┐
│ LocalDateTime │
└───────────────────────────┘
┌────────────────────────────────────────┐
│ OffsetDateTime │
└────────────────────────────────────────┘
┌─────────────────────────────────────────────────────┐
│ ZonedDateTime │
└─────────────────────────────────────────────────────┘分割時(shí)間(ZonedDateTime):2022-02-18T20:41:14.164538200+08:00[Asia/Shanghai]
LocalDate:2022-02-18
LocalTime:T20:41:14.164538200
ZoneOffset:+08:00
ZoneId:[Asia/Shanghai]
import java.time.*;
public class JavaDateTest {public static void main(String[] args) {System.out.println(LocalDate.now()); // 2022-02-19System.out.println(LocalTime.now()); // 18:52:15.279221600System.out.println(LocalDateTime.now()); // 2022-02-19T18:52:15.279221600System.out.println(ZoneOffset.ofHours(8)); // +08:00System.out.println(ZoneId.systemDefault()); // Asia/ShanghaiSystem.out.println(OffsetDateTime.now()); // 2022-02-19T18:52:15.279221600+08:00System.out.println(ZonedDateTime.now()); // 2022-02-19T18:52:15.279221600+08:00[Asia/Shanghai]}
}
java.time.ZoneId
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Set;public class JavaDateTest {public static void main(String[] args) {/*** 常用API:* systemDefault():獲取系統(tǒng)默認(rèn)時(shí)區(qū)的ID* of(String zoneName):根據(jù)各個(gè)地區(qū)的時(shí)區(qū)ID名創(chuàng)建對(duì)象* getAvailableZoneIds():獲取世界各個(gè)地方的時(shí)區(qū)的集合*/System.out.println(ZoneId.systemDefault()); // Asia/ShanghaiSystem.out.println(ZoneId.of("Asia/Kolkata")); // Asia/KolkataSystem.out.println(ZoneId.of("Asia/Tokyo")); // Asia/TokyoSystem.out.println(LocalDateTime.now(ZoneId.of("Asia/Kolkata"))); // 2022-02-19T17:24:39.643968100System.out.println(LocalDateTime.now(ZoneId.of("Asia/Kolkata"))); // 2022-02-19T17:24:39.643968100Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();// [Asia/Aden, America/Cuiaba, Etc/GMT+9, Etc/GMT+8, ...省略后面輸出System.out.println(availableZoneIds);}
}
java.time.ZoneOffset
import java.time.*;
import java.time.temporal.Temporal;public class JavaDateTest {public static void main(String[] args) {System.out.println(ZoneOffset.MAX); // +18:00System.out.println(ZoneOffset.MIN); // -18:00ZoneOffset zone = ZoneOffset.UTC;System.out.println(zone); // ZTemporal temp = zone.adjustInto(ZonedDateTime.now());System.out.println(temp); // 2022-02-19T18:55:40.567526+08:00[Asia/Shanghai]// 獲取5小時(shí)偏移量的ZoneOffset對(duì)象System.out.println(ZoneOffset.ofHours(5)); // +05:00}
}
java.time.OffsetDateTime
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;public class JavaDateTest {public static void main(String[] args) {/*** 最大/最小值* 偏移量的最大值是+18,最小值是-18,這是由ZoneOffset內(nèi)部的限制決定的。*/OffsetDateTime min = OffsetDateTime.MIN;OffsetDateTime max = OffsetDateTime.MAX;// OffsetDateTime最小值:-999999999-01-01T00:00+18:00System.out.println("OffsetDateTime最小值:" + min);// OffsetDateTime最大值:+999999999-12-31T23:59:59.999999999-18:00System.out.println("OffsetDateTime最大值:" + max);// +18:00:-999999999-1-1System.out.println(min.getOffset() + ":" + min.getYear() + "-" + min.getMonthValue() + "-" + min.getDayOfMonth());// -18:00:999999999-12-31System.out.println(max.getOffset() + ":" + max.getYear() + "-" + max.getMonthValue() + "-" + max.getDayOfMonth());/*** ZoneOffset的實(shí)例化*/// 當(dāng)前位置偏移量的本地時(shí)間:2022-02-19T22:31:13.539368500+08:00System.out.println("當(dāng)前位置偏移量的本地時(shí)間:" + OffsetDateTime.now());// 偏移量-4(紐約)的本地時(shí)間::2022-02-19T22:31:13.539368500-04:00System.out.println("偏移量-4(紐約)的本地時(shí)間::" + OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.of("-4")));// 紐約時(shí)區(qū)的本地時(shí)間:2022-02-19T09:31:13.539368500-05:00System.out.println("紐約時(shí)區(qū)的本地時(shí)間:" + OffsetDateTime.now(ZoneId.of("America/New_York")));/*** 轉(zhuǎn)換:LocalDateTime -> OffsetDateTime* 通過此例值得注意的是:LocalDateTime#atOffset()/atZone()只是增加了偏移量/時(shí)區(qū),本地時(shí)間是并沒有改變的。* 若想實(shí)現(xiàn)本地時(shí)間到其它偏移量的對(duì)應(yīng)的時(shí)間只能通過其ofInstant()系列構(gòu)造方法。*/LocalDateTime localDateTime = LocalDateTime.of(2021, 12, 12, 18, 00, 00);// 當(dāng)前時(shí)區(qū)(北京)時(shí)間為:2021-12-12T18:00System.out.println("當(dāng)前時(shí)區(qū)(北京)時(shí)間為:" + localDateTime);// 轉(zhuǎn)換為偏移量為 -4的OffsetDateTime時(shí)間:(-4地方的晚上18點(diǎn))// -4偏移量地方的晚上18點(diǎn)(方式一):2021-12-12T18:00-04:00System.out.println("-4偏移量地方的晚上18點(diǎn)(方式一):" + OffsetDateTime.of(localDateTime, ZoneOffset.ofHours(-4)));// -4偏移量地方的晚上18點(diǎn)(方式二):2021-12-12T18:00-04:00System.out.println("-4偏移量地方的晚上18點(diǎn)(方式二):" + localDateTime.atOffset(ZoneOffset.ofHours(-4)));// 轉(zhuǎn)換為偏移量為 -4的OffsetDateTime時(shí)間:(北京時(shí)間晚上18:00 對(duì)應(yīng)的-4地方的時(shí)間點(diǎn))// 當(dāng)前地區(qū)對(duì)應(yīng)的-4地方的時(shí)間:2021-12-12T06:00-04:00System.out.println("當(dāng)前地區(qū)對(duì)應(yīng)的-4地方的時(shí)間:" + OffsetDateTime.ofInstant(localDateTime.toInstant(ZoneOffset.ofHours(8)), ZoneOffset.ofHours(-4)));/*** 轉(zhuǎn)換:OffsetDateTime -> LocalDateTime*/OffsetDateTime offsetDateTime = OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.ofHours(-4));// -4偏移量時(shí)間為:2022-02-19T22:39:14.442577-04:00System.out.println("-4偏移量時(shí)間為:" + offsetDateTime);// 轉(zhuǎn)為LocalDateTime 注意:時(shí)間還是未變的哦// LocalDateTime的表示形式:2022-02-19T22:39:14.442577System.out.println("LocalDateTime的表示形式:" + offsetDateTime.toLocalDateTime());}
}
java.time.ZonedDateTime
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;public class JavaDateTest {public static void main(String[] args) {// 獲取系統(tǒng)的默認(rèn)時(shí)區(qū)編號(hào)System.out.println(ZoneId.systemDefault());// 獲取本地默認(rèn)時(shí)區(qū)國家的的日期System.out.println("本地時(shí)區(qū)的日期時(shí)間:" + LocalDateTime.now()); // 本地時(shí)區(qū)的日期時(shí)間:2022-02-18T19:17:37.416345200/*** 實(shí)例化ZonedDateTime對(duì)象:* 一種是通過now()方法返回當(dāng)前時(shí)間,一種是通過of()方法放回指定時(shí)間。對(duì)會(huì)帶上時(shí)區(qū)ZoneId對(duì)象* ZonedDateTime now()* ZonedDateTime now(ZoneId zone)* ZonedDateTime now(Clock clock)* ZonedDateTime of(LocalDate date, LocalTime time, ZoneId zone)* ZonedDateTime of(LocalDateTime localDateTime, ZoneId zone)* ZonedDateTime of(int year, int month, int dayOfMonth,int hour, int minute, int second, int nanoOfSecond, ZoneId zone)*/ZonedDateTime zbj1 = ZonedDateTime.now(); // 默認(rèn)時(shí)區(qū)ZonedDateTime zny1 = ZonedDateTime.now(ZoneId.of("America/New_York")); // 用指定時(shí)區(qū)獲取當(dāng)前時(shí)間System.out.println(zbj1); // 2022-02-18T20:41:14.164538200+08:00[Asia/Shanghai]System.out.println(zny1); // 2022-02-18T07:41:14.164538200-05:00[America/New_York]/*** 另一種方式是通過給一個(gè)LocalDateTime附加一個(gè)ZoneId,就可以變成ZonedDateTime:*/LocalDateTime ldt = LocalDateTime.of(2019, 9, 15, 15, 16, 17);ZonedDateTime zbj2 = ldt.atZone(ZoneId.systemDefault());ZonedDateTime zny2 = ldt.atZone(ZoneId.of("America/New_York"));// 以這種方式創(chuàng)建的ZonedDateTime,它的日期和時(shí)間與LocalDateTime相同,但附加的時(shí)區(qū)不同,因此是兩個(gè)不同的時(shí)刻:System.out.println(zbj2); // 2019-09-15T15:16:17+08:00[Asia/Shanghai]System.out.println(zny2); // 2019-09-15T15:16:17-04:00[America/New_York]/*** 對(duì)比LocalDateTime和ZonedDateTime都設(shè)置時(shí)區(qū)的情況*/// 根據(jù)時(shí)區(qū),獲得指定時(shí)區(qū)的當(dāng)前時(shí)間(可以理解為還是本地時(shí)區(qū),所以輸出不顯示時(shí)區(qū))LocalDateTime localDateTime = LocalDateTime.now(ZoneId.of("America/Phoenix"));System.out.println(localDateTime); // 2022-02-18T04:17:37.431349500// 獲取指定時(shí)區(qū),獲得指定時(shí)區(qū)的當(dāng)前時(shí)間(這個(gè)是把當(dāng)前時(shí)間指定到固定的時(shí)區(qū))ZonedDateTime zonedDateTime = LocalDateTime.now().atZone(ZoneId.of("Europe/Monaco"));System.out.println(zonedDateTime); // 2022-02-18T19:17:37.416345200+01:00[Europe/Monaco]/*** 時(shí)區(qū)轉(zhuǎn)換:* 要轉(zhuǎn)換時(shí)區(qū),通過ZonedDateTime的withZoneSameInstant()將關(guān)聯(lián)時(shí)區(qū)轉(zhuǎn)換到另一個(gè)時(shí)區(qū),轉(zhuǎn)換后日期和時(shí)間都會(huì)相應(yīng)調(diào)整。* 下面的代碼演示了如何將北京時(shí)間轉(zhuǎn)換為紐約時(shí)間:* 要特別注意,時(shí)區(qū)轉(zhuǎn)換的時(shí)候,由于夏令時(shí)的存在,不同的日期轉(zhuǎn)換的結(jié)果很可能是不同的。這是北京時(shí)間9月15日的轉(zhuǎn)換結(jié)果:* 下面兩次轉(zhuǎn)換后的紐約時(shí)間有1小時(shí)的夏令時(shí)時(shí)差( 涉及到時(shí)區(qū)時(shí),千萬不要自己計(jì)算時(shí)差,否則難以正確處理夏令時(shí))*/// 設(shè)置中國時(shí)區(qū)時(shí)間9月15日:ZonedDateTime zbj3 = ZonedDateTime.of(2020, 9, 15, 15, 16, 17, 00, ZoneId.of("Asia/Shanghai"));// 轉(zhuǎn)換為紐約時(shí)間:ZonedDateTime zny3 = zbj3.withZoneSameInstant(ZoneId.of("America/New_York"));System.out.println(zbj3); // 2020-09-15T15:16:17+08:00[Asia/Shanghai]System.out.println(zny3); // 2020-09-15T03:16:17-04:00[America/New_York]// 設(shè)置中國時(shí)區(qū)時(shí)間11月15日:ZonedDateTime zbj4 = ZonedDateTime.of(2020, 11, 15, 15, 16, 17, 00, ZoneId.of("Asia/Shanghai"));// 轉(zhuǎn)換為紐約時(shí)間:ZonedDateTime zny4 = zbj4.withZoneSameInstant(ZoneId.of("America/New_York"));System.out.println(zbj4); // 2020-11-15T15:16:17+08:00[Asia/Shanghai]System.out.println(zny4); // 2020-11-15T02:16:17-05:00[America/New_York]/*** 訪問與設(shè)置ZonedDateTime對(duì)象的時(shí)間(與LocalDateTime用法基本一致, 案例直接參考LocalDateTime)** 1.常用的getXxx()系列操作,獲得日期:* int getYear() 獲取當(dāng)前日期的年份* Month getMonth() 獲取當(dāng)前日期的月份對(duì)象(返回一個(gè)Month枚舉值)* int getMonthValue() 獲取當(dāng)前日期是第幾月(1-12)* int getDayOfMonth() 表示該對(duì)象表示的?期是這個(gè)?第?天(1-31)* DayOfWeek getDayOfWeek() 表示該對(duì)象表示的日期是星期幾(返回一個(gè)DayOfWeek枚舉值)* int getDayOfYear() 表示該對(duì)象表示的日期是今年第幾天(1-366)* int getHour() 獲取當(dāng)前時(shí)間小時(shí)數(shù)* int getMinute() 獲取當(dāng)前時(shí)間分鐘數(shù)* int getSecond() 獲取當(dāng)前時(shí)間秒值* int getNano() 把獲取到的當(dāng)前時(shí)間的秒數(shù)換算成納秒** 2.常用的setXxx()系列操作,設(shè)置日期:* ZonedDateTime withYear(int year) 指定對(duì)象的年份* ZonedDateTime withMonth(int month) 指定對(duì)象的月份* ZonedDateTime withDayOfMonth(int dayOfMonth) 指定對(duì)象在當(dāng)月的日期* ZonedDateTime withDayOfYear(int dayOfYear) 指定對(duì)象在當(dāng)年的日期* ZonedDateTime withHour(int hour) 指定對(duì)象的小時(shí)數(shù)* ZonedDateTime withMinute(int minute) 指定對(duì)象的分鐘數(shù)* ZonedDateTime withSecond(int second) 指定對(duì)象在當(dāng)?的秒數(shù)* ZonedDateTime withNano(int nanoOfSecond) 指定對(duì)象在當(dāng)年的納秒數(shù)** 3.常用的plusXxx()系列操作,增加時(shí)間的方法:* ZonedDateTime plusYears(long years) 增加指定年份數(shù)* ZonedDateTime plusMonths(long months) 增加指定?份數(shù)* ZonedDateTime plusDays(long days) 增加指定天數(shù)* ZonedDateTime plusWeeks(long weeks) 增加指定周數(shù)* ZonedDateTime plusHours(long hours) 增加指定小時(shí)* ZonedDateTime plusMinutes(long minutes) 增加指定分鐘* ZonedDateTime plusSeconds(long seconds) 增加指定秒* ZonedDateTime plusNanos(long nanos) 增加指定納秒** 4.常用的minusXxx()系列操作,減少時(shí)間的方法:* ZonedDateTime minusYears(long years) 減去指定年份* ZonedDateTime minusMonths(long months) 減去指定月份* ZonedDateTime minusDays(long days) 減去指定天數(shù)* ZonedDateTime minusWeeks(long weeks) 減去指定周數(shù)* ZonedDateTime minusHours(long hours) 減去指定小時(shí)* ZonedDateTime minusMinutes(long minutes) 減去指定分鐘* ZonedDateTime minusSeconds(long seconds) 減去指定秒* ZonedDateTime minusNanos(long nanos) 減去指定納秒*/// 案例直接參考LocalDateTime}
}
時(shí)間間隔
java.time.Duration(時(shí)間值)
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;public class JavaDateTest {public static void main(String[] args) {/*** 實(shí)例化指定單位的持續(xù)時(shí)間對(duì)象* 注意: 默認(rèn)的打印結(jié)果為ISO國際標(biāo)準(zhǔn)化組織規(guī)定的日期格式,PT2H中的H,表示Hour小時(shí),M代表Minute分鐘,S代表Second秒數(shù)*/Duration durationDays1 = Duration.ofDays(10); // 10天Duration durationDays2 = Duration.of(10, ChronoUnit.DAYS); // 10天System.out.println(durationDays1); // PT240HSystem.out.println(durationDays2); // PT240HDuration durationHours1 = Duration.ofHours(1); // 1小時(shí)Duration durationHours2 = Duration.of(1, ChronoUnit.HOURS); // 1小時(shí)System.out.println(durationHours1); // PT1HSystem.out.println(durationHours2); // PT1HDuration durationMinutes1 = Duration.ofMinutes(1); // 1分Duration durationMinutes2 = Duration.of(1, ChronoUnit.MINUTES); // 1分System.out.println(durationMinutes1); // PT1MSystem.out.println(durationMinutes2); // PT1MDuration durationSeconds1 = Duration.ofSeconds(1); // 1秒Duration durationSeconds2 = Duration.of(1, ChronoUnit.SECONDS); // 1秒System.out.println(durationSeconds1); // PT1SSystem.out.println(durationSeconds2); // PT1SDuration durationMillis1 = Duration.ofMillis(1000); // 1000毫秒Duration durationMillis2 = Duration.of(1000, ChronoUnit.MILLIS); // 1000毫秒System.out.println(durationMillis1); // PT1SSystem.out.println(durationMillis2); // PT1SDuration durationNanos1 = Duration.ofNanos(100000000); // 10000000納秒Duration durationNanos2 = Duration.of(100000000, ChronoUnit.NANOS); // 10000000納秒System.out.println(durationNanos1); // PT0.1SSystem.out.println(durationNanos2); // PT0.1SDuration durationFrom = Duration.from(ChronoUnit.DAYS.getDuration());System.out.println(durationFrom); // PT24H/*** 獲取指定單位的持續(xù)時(shí)間* long toDays() 這段時(shí)間的總天數(shù)* long toHours() 這段時(shí)間的小時(shí)數(shù)* long toMinutes() 這段時(shí)間的分鐘數(shù)* long toSeconds() 這段時(shí)間的秒數(shù)* long toMillis() 這段時(shí)間的毫秒數(shù)* long toNanos() 這段時(shí)間的納秒數(shù)* String toString() 此持續(xù)時(shí)間的字符串表示形式,使用基于ISO-8601秒*的表示形式,例如 PT8H6M12.345S*/Duration durationOne = Duration.ofDays(1); // 設(shè)置1天的時(shí)間System.out.println("toDay天 = "+ durationOne.toDays()); // toDay時(shí)間 = 1System.out.println("toHours時(shí) = "+ durationOne.toHours()); // toHours時(shí)間 = 24System.out.println("toMinutes分 = "+ durationOne.toMinutes()); // toMinutes時(shí)間 = 1440System.out.println("toMinutes秒 = "+ durationOne.toSeconds()); // toMinutes秒 = 86400System.out.println("toMillis毫秒 = "+ durationOne.toMillis()); // toMillis時(shí)間 = 86400000System.out.println("toNanos納秒 = "+ durationOne.toNanos()); // toNanos時(shí)間 = 86400000000000System.out.println("toString格式 = "+ durationOne.toString()); // toString時(shí)間 = PT24H/*** 獲取2個(gè)時(shí)間點(diǎn)之間差值的持續(xù)時(shí)間* Duration.between()方法創(chuàng)建Duration對(duì)象,注意這個(gè)天數(shù)是可以負(fù)數(shù),意味著如果開始時(shí)間比結(jié)束時(shí)間更后面就會(huì)得到負(fù)數(shù)天數(shù)*/LocalDateTime from = LocalDateTime.of(2017, 01, 1, 00, 0, 0); // 2017-01-01 00:00:00LocalDateTime to = LocalDateTime.of(2019, 9, 12, 14, 28, 0); // 2019-09-12 14:28:00Duration duration1 = Duration.between(from, to); // 表示從 from 到 to 這段時(shí)間(第?個(gè)參數(shù)減第?個(gè)參數(shù))System.out.println(duration1.toDays()); // 984System.out.println(duration1.toHours()); // 23630System.out.println(duration1.toMinutes()); // 1417828System.out.println(duration1.getSeconds()); // 85069680System.out.println(duration1.toMillis()); // 85069680000System.out.println(duration1.toNanos()); // 85069680000000000/*** Duration時(shí)間的加減,可以參考LocalDateTime中的plusXxx、minusXxx和withXxx()系列的方法* 注意: Duration包含兩部分:seconds秒,nanos納秒,它們的組合表達(dá)了時(shí)間長度。所以withXxx()只有withSeconds()和withNanos()方法*/System.out.println(Duration.ofDays(4).withSeconds(360).toHours()); // 加8小時(shí)(4天8小時(shí)):輸出:0System.out.println(Duration.ofDays(4).plusHours(8).toHours()); // 加8小時(shí)(4天8小時(shí)):輸出:104System.out.println(Duration.ofDays(4).minusHours(8).toHours()); // 加8小時(shí)(4天8小時(shí)):輸出:88/*** Duration可以接收:LocalDate、LocalTime、LocalDateTime、Instant* Duration只能處理兩個(gè)Instant、LocalTime, LocalDateTime, ZonedDateTime,* 參數(shù)不能混搭,混搭會(huì)報(bào)異常,如果傳入的是LocalDate,將會(huì)拋出異常*/Duration.between(LocalTime.now(), LocalTime.now());Duration.between(LocalDateTime.now(), LocalDateTime.now());Duration.between(Instant.now(), Instant.now());}
}
java.time.Period(日期值)
import java.time.Duration;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;public class JavaDateTest {public static void main(String[] args) {/*** 實(shí)例化指定單位的持續(xù)日期對(duì)象* 注意: 默認(rèn)的打印結(jié)果為ISO國際標(biāo)準(zhǔn)化組織規(guī)定的日期格式,P3Y2M1D中的,Y表示Year年,M代表Month月,D代表Day天*/System.out.println(Period.between(LocalDate.now(), LocalDate.now())); // P0DSystem.out.println(Period.of(1,2,3)); // P1Y2M3DSystem.out.println(Period.ofYears(1)); // P1YSystem.out.println(Period.ofMonths(2)); // P2MSystem.out.println(Period.ofDays(25)); // P25DSystem.out.println(Period.ofWeeks(4)); // P28DSystem.out.println(Period.from(Period.of(3, 2, 1))); // P3Y2M1D/*** 獲取指定單位的持續(xù)時(shí)間*/Period periodYears = Period.ofYears(1); // 設(shè)置1年的時(shí)間System.out.println(periodYears.getYears()); // 1System.out.println(periodYears.getMonths()); // 0System.out.println(periodYears.getDays()); // 0System.out.println(periodYears.get(ChronoUnit.YEARS)); // 1System.out.println(periodYears.get(ChronoUnit.MONTHS)); // 0System.out.println(periodYears.get(ChronoUnit.DAYS)); // 0System.out.println(periodYears.getChronology()); // 獲取此Period的年表,即ISO日歷系統(tǒng):ISOSystem.out.println(periodYears.getUnits()); // 查看支持的枚舉類型:[Years, Months, Days]/*** Period時(shí)間的加減,可以參考LocalDateTime中的plusXxx、minusXxx和withXxx()系列的方法*/System.out.println(Period.of(1,2,3).withYears(8).getYears()); // 3System.out.println(Period.of(1,2,3).withMonths(8).getMonths()); // 3System.out.println(Period.of(1,2,3).withDays(8).getDays()); // 8System.out.println(Period.of(1,2,3).plusYears(8).getYears()); // 3System.out.println(Period.of(1,2,3).plusMonths(8).getMonths()); // 3System.out.println(Period.of(1,2,3).plusDays(8).getDays()); // 11System.out.println(Period.of(1,2,3).minusYears(8).getYears()); // 3System.out.println(Period.of(1,2,3).minusMonths(8).getMonths()); // 3System.out.println(Period.of(1,2,3).minusDays(8).getDays()); // -5}
}
TemporalAdjuster 矯正器
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;public class JavaDateTest {public static void main(String[] args) {LocalDateTime now = LocalDateTime.now(); // 首先獲取當(dāng)前時(shí)間System.out.println("當(dāng)前時(shí)間:"+now); // 當(dāng)前時(shí)間:2022-02-17T22:01:45.718728600/*** 方式一:使用TemporalAdjuster接口自定義日期方式實(shí)現(xiàn)*/TemporalAdjuster adJuster = (temporal) -> {LocalDateTime dateTime = (LocalDateTime) temporal;DayOfWeek dayOfWeek = dateTime.getDayOfWeek(); // 先獲取周幾if (DayOfWeek.FRIDAY.equals(dayOfWeek)) {return dateTime.plusDays(3); // 周五加三天等于工作日} else if (DayOfWeek.SATURDAY.equals(dayOfWeek)) {return dateTime.plusDays(2); // 周六加兩天}return dateTime.plusDays(1); // 其他均加一天};// 下一個(gè)工作日:2022-02-18T22:01:45.718728600System.out.println("下一個(gè)工作日:" + now.with(adJuster));/*** 方式二:使用TemporalAdjusters工具類提供的日期來實(shí)現(xiàn)*/LocalDateTime with1 = now.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));// 下周日:2022-02-20T22:01:45.718728600System.out.println("下周日:" + with1);LocalDateTime with2 = now.with(TemporalAdjusters.firstDayOfMonth());// 這個(gè)月的第一天:2022-02-01T22:01:45.718728600System.out.println("這個(gè)月的第一天:" + with2);LocalDateTime with3 = now.with(TemporalAdjusters.firstDayOfNextMonth());// 下個(gè)月的第一天:2022-03-01T22:01:45.718728600System.out.println("下個(gè)月的第一天:" + with3);}
}