您好,登錄后才能下訂單哦!
這篇文章主要介紹“Java基礎(chǔ)篇之如何使用日期與時間API技術(shù)”,在日常操作中,相信很多人在Java基礎(chǔ)篇之如何使用日期與時間API技術(shù)問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Java基礎(chǔ)篇之如何使用日期與時間API技術(shù)”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
在系統(tǒng)開發(fā)中,日期與時間作為重要的業(yè)務(wù)因素,起到十分關(guān)鍵的作用,例如同一個時間節(jié)點下的數(shù)據(jù)生成,基于時間范圍的各種數(shù)據(jù)統(tǒng)計和分析,集群節(jié)點統(tǒng)一時間避免超時等。
在時間和日期中有幾個關(guān)鍵概念:
日期:通常年月日的組合表示當前日期。
時間:通常時分秒的組合表示當前時間。
時區(qū):世界各國家與地區(qū)經(jīng)度不同,劃分24個標準時區(qū),相鄰時區(qū)的時間相差一個小時。
時間戳:從UTC時間的1970-1-1 00:00:00
起到現(xiàn)在的總秒數(shù)。
日期和時間的用法在系統(tǒng)中通常是獲取時間和一些常見的計算與格式轉(zhuǎn)換處理,在一些垮時區(qū)的業(yè)務(wù)中就會變的復(fù)雜很多,例如在電商業(yè)務(wù)中的全球貿(mào)易或者海淘等。
基礎(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 2021 1611904285848
計算規(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()); } }
年份:當前時間減去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 { // 默認轉(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); // 解析時間 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初始版本就使用的日期和時間,Date類一直在項目中使用,但是相關(guān)API的方法都已經(jīng)基本廢棄,通常使用一些二次封裝的時間組件。該API的設(shè)計堪稱Java中的最爛。
Calendar作為一個抽象類,定義日期時間相關(guān)轉(zhuǎn)換與計算的方法,這個類目測
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實現(xiàn),簡化Date的功能側(cè)重對日期與時間的實體封裝,Calendar復(fù)雜相關(guān)計算策略,DateFormat依舊用來做格式處理。但是Calendar依舊很少被使用,上述基礎(chǔ)API就已經(jīng)是很好的說明了。
Java8之后的版本中,核心API類包括LocalDate-日期、LocalTime-時間、LocalDateTime-日期加時間。
LocalDate:日期描述是final修飾的不可變類,默認格式y(tǒng)yyy-MM-dd。
LocalTime:時間描述是final修飾的不可變類,默認格式hh:mm:ss.zzz。
LocalDateTime:日期與時間描述final修飾的不可變類。
public class DateTime05 { public static void main(String[] args) { // 日期:年-月-日 System.out.println(LocalDate.now()); // 時間:時-分-秒-毫秒 System.out.println(LocalTime.now()); // 日期時間:年-月-日 時-分-秒-毫秒 System.out.println(LocalDateTime.now()); // 日期節(jié)點獲取 LocalDate localDate = LocalDate.now(); System.out.println("[" + localDate.getYear() + "年];[" + localDate.getMonthValue() + "月];[" + localDate.getDayOfMonth()+"日]"); // 計算方法 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)); // 時間比較 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)); // 日期和時間格式 LocalDateTime localDateTime = LocalDateTime.now() ; LocalDate myLocalDate = localDateTime.toLocalDate(); LocalTime myLocalTime = localDateTime.toLocalTime(); System.out.println("日期:" + myLocalDate); System.out.println("時間:" + myLocalTime); } }
如果作為JodaTime組件的深度用戶,對這個幾個API使用基本無壓力。
時間戳也是業(yè)務(wù)中常用的方式,基于Long類型表示時間,在很多時候遠比常規(guī)日期與時間的格式更好用。
public class DateTime06 { public static void main(String[] args) { // 精確到毫秒級別 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()); } }
這里需要注意的是在實際業(yè)務(wù)中由于獲取時間戳的方式是多樣的,所以建議統(tǒng)一工具方法,和規(guī)定精確度,避免部分精確到秒部分精確到毫秒的問題,這樣可以規(guī)避在使用時相互轉(zhuǎn)換的情況。
在Java8之前JodaTime組件是大部分系統(tǒng)中的常見選擇,有很多方便好用的日期與時間的處理方法封裝。
基礎(chǔ)依賴:
<dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> </dependency>
在joda-time提供的組件之上做一個簡單的工具類封裝,保證業(yè)務(wù)處理風格統(tǒng)一。
public class JodaTimeUtil { // 時間格式 public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; private JodaTimeUtil (){} // 獲取當前時間 public static DateTime getCurrentTime (){ return new DateTime() ; } // 獲取指定時間 public static DateTime getDateTime (Object obj){ return new DateTime(obj) ; } // 把時間以指定格式轉(zhuǎn)換為字符串 public static String getNowDate (Date date, String format){ return new DateTime(date).toString(format) ; } // 獲取星期時間 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-parent GitEE·地址 https://gitee.com/cicadasmile/java-base-parent
到此,關(guān)于“Java基礎(chǔ)篇之如何使用日期與時間API技術(shù)”的學習就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。