在Java編程中,對於時間格式的轉換是一項很基礎但也很重要的操作。本文將從多個方面,介紹Java中時間格式的轉換應用實例。
一、格式化時間
在Java中,我們可以使用SimpleDateFormat類對一個日期/時間進行格式化:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String formattedDate = formatter.format(new Date()); System.out.println("Formatted date is: " + formattedDate);
上述代碼中,我們定義了一個SimpleDateFormat對象來指定輸出日期格式,然後使用format方法將時間轉換為字元串並輸出。
我們還可以指定不同的日期格式,以滿足不同的需求。
SimpleDateFormat formatter2 = new SimpleDateFormat("dd MMM yyyy"); String formattedDate2 = formatter2.format(new Date()); System.out.println("Formatted date is: " + formattedDate2);
上述代碼中,我們將日期格式化為「dd MMM yyyy」的形式。此外,我們還可以使用SimpleDateFormat類來解析指定格式的字元串,並將其轉換為日期對象。
二、時間戳轉換
Unix 時間戳是一個從 1970 年 1 月 1 日 00:00:00 GMT 到指定時間的秒數。Java中可以使用時間戳來表示時間,也可以將時間戳轉換為指定格式的日期。
以下是將 Unix 時間戳轉換為日期的示例:
long unixTimestamp = 1630473600; Date date = new Date(unixTimestamp * 1000L); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); String formattedDate = sdf.format(date); System.out.println("Converted date is: " + formattedDate);
上述代碼中,我們使用Date構造函數將時間戳轉換為日期對象,並使用SimpleDateFormat類對日期進行格式化,最後輸出轉換後的日期。
同時,我們也可以將指定格式的日期轉換為 Unix 時間戳:
String dateStr = "2021-09-01 00:00:00"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = sdf.parse(dateStr); long unixTimestamp = date.getTime() / 1000; System.out.println("Unix timestamp is: " + unixTimestamp);
三、獲取當前時間
在Java中,我們可以通過以下方式獲取當前時間:
Date currentDate = new Date(); System.out.println("Current date is: " + currentDate);
以上代碼將返回當前系統時間。如果你需要獲取格式化後的日期,可以參考第一部分的示例。
另外,我們也可以通過使用Calendar類獲取當前時間,並進行相應的操作。例如,我們可以獲取當前時間的年份、月份、日期等:
Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); System.out.println("Current date is: " + year + "-" + month + "-" + dayOfMonth + " " + hourOfDay + ":" + minute + ":" + second);
以上代碼將返回當前系統時間的年份、月份、日期、時、分、秒等信息。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/303509.html