java localtime是什么,讓我們一起了解一下?
localtime是把從1970-1-1零點零分到當前時間系統所偏移的秒數時間轉換為本地時間,而gmtime函數轉換后的時間沒有經過時區變換,是UTC時間,在java中localtime() 函數返回本地時間(一個數組)。
我們平時在程序里面所見到的UTC時間,就是零時區的時間,它的全稱是Coordinated Universal Time ,即世界協調時間。另一個常見的縮寫是GMT,即格林威治標準時間,格林威治位于零時區,因此,我們平時說的UTC時間和GMT時間在數值上面都是一樣的。
而且從Java8開始,推出了LocalDate、LocalTime、LocalDateTime這三個工具類,實現了更好地時間處理。
?那么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)?{ //獲取當前時區的日期 LocalDate?localDate?=?LocalDate.now(); System.out.println("localDate:?"?+?localDate); //時間 LocalTime?localTime?=?LocalTime.now(); System.out.println("localTime:?"?+?localTime); //根據上面兩個對象,獲取日期時間 LocalDateTime?localDateTime?=?LocalDateTime.of(localDate,localTime); System.out.println("localDateTime:?"?+?localDateTime); //使用靜態方法生成此對象 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)); //轉化為時間戳(秒) long?epochSecond?=?localDateTime2.toEpochSecond(ZoneOffset.of("+8")); //轉化為毫秒 long?epochMilli?=?localDateTime2.atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli(); System.out.println("時間戳為:(秒)?"?+?epochSecond?+?";?(毫秒):?"?+?epochMilli); //時間戳(毫秒)轉化成LocalDateTime Instant?instant?=?Instant.ofEpochMilli(epochMilli); LocalDateTime?localDateTime3?=?LocalDateTime.ofInstant(instant,?ZoneOffset.systemDefault()); System.out.println("時間戳(毫秒)轉化成LocalDateTime:?"?+?localDateTime3.format(formatter)); //時間戳(秒)轉化成LocalDateTime Instant?instant2?=?Instant.ofEpochSecond(epochSecond); LocalDateTime?localDateTime4?=?LocalDateTime.ofInstant(instant2,?ZoneOffset.systemDefault()); System.out.println("時間戳(秒)轉化成LocalDateTime:?"?+?localDateTime4.format(formatter)); } }
以上就是小編今天的分享了,希望可以幫助到大家。