java localtime是什么,讓我們一起了解一下?
localtime是把從1970-1-1零點零分到當(dāng)前時間系統(tǒng)所偏移的秒數(shù)時間轉(zhuǎn)換為本地時間,而gmtime函數(shù)轉(zhuǎn)換后的時間沒有經(jīng)過時區(qū)變換,是UTC時間,在java中l(wèi)ocaltime() 函數(shù)返回本地時間(一個數(shù)組)。
我們平時在程序里面所見到的UTC時間,就是零時區(qū)的時間,它的全稱是Coordinated Universal Time ,即世界協(xié)調(diào)時間。另一個常見的縮寫是GMT,即格林威治標(biāo)準(zhǔn)時間,格林威治位于零時區(qū),因此,我們平時說的UTC時間和GMT時間在數(shù)值上面都是一樣的。
而且從Java8開始,推出了LocalDate、LocalTime、LocalDateTime這三個工具類,實現(xiàn)了更好地時間處理。
?那么LocalTime是如何使用的?
工具類的獲取與使用代碼如下:
import?java.time.Instant; import?java.time.LocalDate; import?java.time.LocalDateTime; import?java.time.LocalTime; import?java.time.ZoneOffset; import?java.time.format.DateTimeFormatter; ? public?class?TestLocalTime?{ public?static?void?main(String[]?args)?{ //獲取當(dāng)前時區(qū)的日期 LocalDate?localDate?=?LocalDate.now(); System.out.println("localDate:?"?+?localDate); //時間 LocalTime?localTime?=?LocalTime.now(); System.out.println("localTime:?"?+?localTime); //根據(jù)上面兩個對象,獲取日期時間 LocalDateTime?localDateTime?=?LocalDateTime.of(localDate,localTime); System.out.println("localDateTime:?"?+?localDateTime); //使用靜態(tài)方法生成此對象 LocalDateTime?localDateTime2?=?LocalDateTime.now(); System.out.println("localDateTime2:?"?+?localDateTime2); //格式化時間 DateTimeFormatter?formatter?=?DateTimeFormatter.ofPattern("YYYY-MM-dd?HH:mm:ss"); System.out.println("格式化之后的時間:?"?+?localDateTime2.format(formatter)); //轉(zhuǎn)化為時間戳(秒) long?epochSecond?=?localDateTime2.toEpochSecond(ZoneOffset.of("+8")); //轉(zhuǎn)化為毫秒 long?epochMilli?=?localDateTime2.atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli(); System.out.println("時間戳為:(秒)?"?+?epochSecond?+?";?(毫秒):?"?+?epochMilli); //時間戳(毫秒)轉(zhuǎn)化成LocalDateTime Instant?instant?=?Instant.ofEpochMilli(epochMilli); LocalDateTime?localDateTime3?=?LocalDateTime.ofInstant(instant,?ZoneOffset.systemDefault()); System.out.println("時間戳(毫秒)轉(zhuǎn)化成LocalDateTime:?"?+?localDateTime3.format(formatter)); //時間戳(秒)轉(zhuǎn)化成LocalDateTime Instant?instant2?=?Instant.ofEpochSecond(epochSecond); LocalDateTime?localDateTime4?=?LocalDateTime.ofInstant(instant2,?ZoneOffset.systemDefault()); System.out.println("時間戳(秒)轉(zhuǎn)化成LocalDateTime:?"?+?localDateTime4.format(formatter)); } }
以上就是小編今天的分享了,希望可以幫助到大家。