更新時間:2019-12-13 11:39:50 來源:動力節(jié)點(diǎn) 瀏覽3078次
1、System.currentTimeMillis()
獲取標(biāo)準(zhǔn)時間可以通過System.currentTimeMillis()方法獲取,此方法不受時區(qū)影響,得到的結(jié)果是時間戳格式的。
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
Date date = new Date(System.currentTimeMillis());
System.out.println(formatter.format(date));
2、java.util.Date
在Java中,獲取當(dāng)前日期最簡單的方法之一就是直接實(shí)例化位于Java包java.util的Date類。
Date date = new Date(); // this object contains the current date value
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
System.out.println(formatter.format(date));
3、Calendar API
Calendar類,專門用于轉(zhuǎn)換特定時刻和日歷字段之間的日期和時間。
使用Calendar 獲取當(dāng)前日期和時間非常簡單:
Calendar calendar = Calendar.getInstance(); // gets current instance of the calendar
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
System.out.println(formatter.format(calendar.getTime()));
4、Date/Time API
Java 8提供了一個全新的API,用以替換java.util.Date和java.util.Calendar。Date / Time API提供了多個類,幫助我們來完成工作。
LocalDate date = LocalDate.now(); // gets the current date
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
System.out.println(date.format(formatter));
5、Date/Time API
Java 8提供了一個全新的API,用以替換java.util.Date和java.util.Calendar。Date / Time API提供了多個類,幫助我們來完成工作。
LocalTime time = LocalTime.now(); // gets the current time
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
System.out.println(time.format(formatter));
6、LocalDateTime
最后一個是LocalDateTime,也是Java中最常用的Date / Time類,代表前兩個累的組合 - 即日期和時間的值。
LocalDateTime dateTime = LocalDateTime.now(); // gets the current date and time
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
System.out.println(dateTime.format(formatter));
以上就是動力節(jié)點(diǎn)Java培訓(xùn)機(jī)構(gòu)小編介紹的“Java獲取當(dāng)前時間的幾種方法”的內(nèi)容,希望對大家有幫助,如有疑問,請?jiān)诰€咨詢,有專業(yè)老師隨時為你服務(wù)。
相關(guān)文章
零基礎(chǔ)怎么自學(xué)Java,完整版Java學(xué)習(xí)路線圖
你還在糾結(jié)學(xué)Java,是自學(xué)還是去培訓(xùn)班嗎
一個標(biāo)準(zhǔn)的Java程序員如何進(jìn)階?
相關(guān)閱讀
初級 202925
初級 203221
初級 202629
初級 203743