Java 日期與時(shí)間API相關(guān)用法總結(jié)
在系統(tǒng)開發(fā)中,日期與時(shí)間作為重要的業(yè)務(wù)因素,起到十分關(guān)鍵的作用,例如同一個(gè)時(shí)間節(jié)點(diǎn)下的數(shù)據(jù)生成,基于時(shí)間范圍的各種數(shù)據(jù)統(tǒng)計(jì)和分析,集群節(jié)點(diǎn)統(tǒng)一時(shí)間避免超時(shí)等。
在時(shí)間和日期中有幾個(gè)關(guān)鍵概念:
日期:通常年月日的組合表示當(dāng)前日期。 時(shí)間:通常時(shí)分秒的組合表示當(dāng)前時(shí)間。 時(shí)區(qū):世界各國家與地區(qū)經(jīng)度不同,劃分24個(gè)標(biāo)準(zhǔn)時(shí)區(qū),相鄰時(shí)區(qū)的時(shí)間相差一個(gè)小時(shí)。 時(shí)間戳:從UTC時(shí)間的1970-1-1 00:00:00起到現(xiàn)在的總秒數(shù)。日期和時(shí)間的用法在系統(tǒng)中通常是獲取時(shí)間和一些常見的計(jì)算與格式轉(zhuǎn)換處理,在一些垮時(shí)區(qū)的業(yè)務(wù)中就會(huì)變的復(fù)雜很多,例如在電商業(yè)務(wù)中的全球貿(mào)易或者海淘等。
二、JDK原生API1、Date基礎(chǔ)基礎(chǔ)用法
java.sql.Date繼承java.util.Date,相關(guān)方法也大部分直接調(diào)用父類方法。
public class DateTime01 { public static void main(String[] args) { long nowTime = System.currentTimeMillis() ; java.util.Date data01 = new java.util.Date(nowTime); java.sql.Date date02 = new java.sql.Date(nowTime); System.out.println(data01); System.out.println(date02.getTime()); }}打印:Fri Jan 29 15:11:25 CST 20211611904285848
計(jì)算規(guī)則
public class DateTime02 { public static void main(String[] args) { Date nowDate = new Date(); System.out.println('年:'+nowDate.getYear()); System.out.println('月:'+nowDate.getMonth()); System.out.println('日:'+nowDate.getDay()); }}
年份:當(dāng)前時(shí)間減去1900;
public int getYear() { return normalize().getYear() - 1900;}
月份:0-11表示1-12月份;
public int getMonth() { return normalize().getMonth() - 1;}
天份:正常表示;
public int getDay() { return normalize().getDayOfWeek() - BaseCalendar.SUNDAY;}
格式轉(zhuǎn)換
非線程安全的日期轉(zhuǎn)換API,該用法在規(guī)范的開發(fā)中是不允許使用的。
public class DateTime02 { public static void main(String[] args) throws Exception { // 默認(rèn)轉(zhuǎn)換 DateFormat dateFormat01 = new SimpleDateFormat() ; String nowDate01 = dateFormat01.format(new Date()) ; System.out.println('nowDate01='+nowDate01); // 指定格式轉(zhuǎn)換 String format = 'yyyy-MM-dd HH:mm:ss'; SimpleDateFormat dateFormat02 = new SimpleDateFormat(format); String nowDate02 = dateFormat02.format(new Date()) ; System.out.println('nowDate02='+nowDate02); // 解析時(shí)間 String parse = 'yyyy-MM-dd HH:mm'; SimpleDateFormat dateFormat03 = new SimpleDateFormat(parse); Date parseDate = dateFormat03.parse('2021-01-18 16:59:59') ; System.out.println('parseDate='+parseDate); }}
作為JDK初始版本就使用的日期和時(shí)間,Date類一直在項(xiàng)目中使用,但是相關(guān)API的方法都已經(jīng)基本廢棄,通常使用一些二次封裝的時(shí)間組件。該API的設(shè)計(jì)堪稱Java中的最爛。
2、Calendar升級(jí)Calendar作為一個(gè)抽象類,定義日期時(shí)間相關(guān)轉(zhuǎn)換與計(jì)算的方法,這個(gè)類目測
public class DateTime04 { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR,2021); calendar.set(Calendar.MONTH,1); calendar.set(Calendar.DAY_OF_MONTH,12); calendar.set(Calendar.HOUR_OF_DAY,23); calendar.set(Calendar.MINUTE,59); calendar.set(Calendar.SECOND,59); calendar.set(Calendar.MILLISECOND,0); DateFormat dateFormat = new SimpleDateFormat('yyyy-MM-dd HH:mm:ss') ; Date defDate = calendar.getTime(); System.out.println(defDate+'||'+dateFormat.format(defDate)); }}輸出:Fri Feb 12 23:59:59 CST 2021||2021-02-12 23:59:59
直觀感覺,Date中相關(guān)方法遷移Calendar實(shí)現(xiàn),簡化Date的功能側(cè)重對日期與時(shí)間的實(shí)體封裝,Calendar復(fù)雜相關(guān)計(jì)算策略,DateFormat依舊用來做格式處理。但是Calendar依舊很少被使用,上述基礎(chǔ)API就已經(jīng)是很好的說明了。
3、JDK1.8升級(jí)APIJava8之后的版本中,核心API類包括LocalDate-日期、LocalTime-時(shí)間、LocalDateTime-日期加時(shí)間。
LocalDate:日期描述是final修飾的不可變類,默認(rèn)格式y(tǒng)yyy-MM-dd。 LocalTime:時(shí)間描述是final修飾的不可變類,默認(rèn)格式hh:mm:ss.zzz。 LocalDateTime:日期與時(shí)間描述final修飾的不可變類。public class DateTime05 { public static void main(String[] args) { // 日期:年-月-日 System.out.println(LocalDate.now()); // 時(shí)間:時(shí)-分-秒-毫秒 System.out.println(LocalTime.now()); // 日期時(shí)間:年-月-日 時(shí)-分-秒-毫秒 System.out.println(LocalDateTime.now()); // 日期節(jié)點(diǎn)獲取 LocalDate localDate = LocalDate.now(); System.out.println('[' + localDate.getYear() + '年];[' + localDate.getMonthValue() + '月];[' + localDate.getDayOfMonth()+'日]'); // 計(jì)算方法 System.out.println('1年后:' + localDate.plusYears(1)); System.out.println('2月前:' + localDate.minusMonths(2)); System.out.println('3周后:' + localDate.plusWeeks(3)); System.out.println('3天前:' + localDate.minusDays(3)); // 時(shí)間比較 LocalTime localTime1 = LocalTime.of(12, 45, 45); ; LocalTime localTime2 = LocalTime.of(16, 30, 30); ; System.out.println(localTime1.isAfter(localTime2)); System.out.println(localTime2.isAfter(localTime1)); System.out.println(localTime2.equals(localTime1)); // 日期和時(shí)間格式 LocalDateTime localDateTime = LocalDateTime.now() ; LocalDate myLocalDate = localDateTime.toLocalDate(); LocalTime myLocalTime = localDateTime.toLocalTime(); System.out.println('日期:' + myLocalDate); System.out.println('時(shí)間:' + myLocalTime); }}
如果作為JodaTime組件的深度用戶,對這個(gè)幾個(gè)API使用基本無壓力。
4、時(shí)間戳時(shí)間戳也是業(yè)務(wù)中常用的方式,基于Long類型表示時(shí)間,在很多時(shí)候遠(yuǎn)比常規(guī)日期與時(shí)間的格式更好用。
public class DateTime06 { public static void main(String[] args) { // 精確到毫秒級(jí)別 System.out.println(System.currentTimeMillis()); System.out.println(new Date().getTime()); System.out.println(Calendar.getInstance().getTime().getTime()); System.out.println(LocalDateTime.now().toInstant( ZoneOffset.of('+8')).toEpochMilli()); }}
這里需要注意的是在實(shí)際業(yè)務(wù)中由于獲取時(shí)間戳的方式是多樣的,所以建議統(tǒng)一工具方法,和規(guī)定精確度,避免部分精確到秒部分精確到毫秒的問題,這樣可以規(guī)避在使用時(shí)相互轉(zhuǎn)換的情況。
三、JodaTime組件在Java8之前JodaTime組件是大部分系統(tǒng)中的常見選擇,有很多方便好用的日期與時(shí)間的處理方法封裝。
基礎(chǔ)依賴:
<dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId></dependency>
在joda-time提供的組件之上做一個(gè)簡單的工具類封裝,保證業(yè)務(wù)處理風(fēng)格統(tǒng)一。
public class JodaTimeUtil { // 時(shí)間格式 public static final String DATE_FORMAT = 'yyyy-MM-dd HH:mm:ss'; private JodaTimeUtil (){} // 獲取當(dāng)前時(shí)間 public static DateTime getCurrentTime (){ return new DateTime() ; } // 獲取指定時(shí)間 public static DateTime getDateTime (Object obj){ return new DateTime(obj) ; } // 把時(shí)間以指定格式轉(zhuǎn)換為字符串 public static String getNowDate (Date date, String format){ return new DateTime(date).toString(format) ; } // 獲取星期時(shí)間 public static String getWeek (Object date){ DateTime time = getDateTime (date) ; String week = null ; switch (time.getDayOfWeek()) { case DateTimeConstants.SUNDAY: week = '星期日'; break; case DateTimeConstants.MONDAY: week = '星期一'; break; case DateTimeConstants.TUESDAY: week = '星期二'; break; case DateTimeConstants.WEDNESDAY: week = '星期三'; break; case DateTimeConstants.THURSDAY: week = '星期四'; break; case DateTimeConstants.FRIDAY: week = '星期五'; break; case DateTimeConstants.SATURDAY: week = '星期六'; break; default: break; } return week ; }}四、源代碼地址
GitHub·地址https://github.com/cicadasmile/java-base-parentGitEE·地址https://gitee.com/cicadasmile/java-base-parent
以上就是Java 日期與時(shí)間API相關(guān)用法總結(jié)的詳細(xì)內(nèi)容,更多關(guān)于Java 日期與時(shí)間api的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 詳解CSS偽元素的妙用單標(biāo)簽之美2. 使用Spry輕松將XML數(shù)據(jù)顯示到HTML頁的方法3. HTML5 Canvas繪制圖形從入門到精通4. XHTML 1.0:標(biāo)記新的開端5. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究6. 利用CSS3新特性創(chuàng)建透明邊框三角7. asp(vbscript)中自定義函數(shù)的默認(rèn)參數(shù)實(shí)現(xiàn)代碼8. ASP基礎(chǔ)知識(shí)VBScript基本元素講解9. JSP的Cookie在登錄中的使用10. XML入門的常見問題(四)
