1、System.currentTimeMillis()
獲取標(biāo)準(zhǔn)時(shí)間可以通過(guò)System.currentTimeMillis()方法獲取,此方法不受時(shí)區(qū)影響,得到的結(jié)果是時(shí)間戳格式的。
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)前日期最簡(jiǎn)單的方法之一就是直接實(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)換特定時(shí)刻和日歷字段之間的日期和時(shí)間。
使用Calendar 獲取當(dāng)前日期和時(shí)間非常簡(jiǎn)單:
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提供了一個(gè)全新的API,用以替換java.util.Date和java.util.Calendar。Date / Time API提供了多個(gè)類,幫助我們來(lái)完成工作。
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提供了一個(gè)全新的API,用以替換java.util.Date和java.util.Calendar。Date / Time API提供了多個(gè)類,幫助我們來(lái)完成工作。
LocalTime time = LocalTime.now(); // gets the current time
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
System.out.println(time.format(formatter));
6、LocalDateTime
最后一個(gè)是LocalDateTime,也是Java中最常用的Date / Time類,代表前兩個(gè)累的組合 - 即日期和時(shí)間的值。
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));
以上就是天津卓眾教育Java培訓(xùn)機(jī)構(gòu)小編介紹的“Java獲取當(dāng)前時(shí)間的幾種方法”的內(nèi)容,希望對(duì)大家有幫助,如有疑問(wèn),請(qǐng)?jiān)诰€咨詢,有專業(yè)老師隨時(shí)為你服務(wù)。
相關(guān)文章
零基礎(chǔ)怎么自學(xué)Java,完整版Java學(xué)習(xí)路線圖
你還在糾結(jié)學(xué)Java,是自學(xué)還是去培訓(xùn)班嗎
一個(gè)標(biāo)準(zhǔn)的Java程序員如何進(jìn)階?
Java學(xué)習(xí)路線清單,快速進(jìn)階Java
Java編程初學(xué)者要如何進(jìn)階