java 擷取目前日期時間
Java provides two classes to get current date and time – Date and Calendar.
Java提供了兩個類來擷取目前日期和時間-Date和Calendar 。
用Java擷取目前日期 (Get Current Date in Java)
Here is the simple program showing how we can use these classes to get the current date and time in Java.
這是一個簡單的程式,顯示了我們如何使用這些類來擷取Java中的目前日期和時間。
package com.journaldev.util;
import java.util.Calendar;
import java.util.Date;
public class DateAndTimeUtil {
public static void main(String[] args) {
//Get current date using Date
Date date = new Date();
System.out.println("Current date using Date = "+date.toString());
//Get current date using Calendar
Calendar cal = Calendar.getInstance();
System.out.println("Current date using Calendar = "+cal.getTime());
//Get current time in milliseconds
System.out.println("Current time in milliseconds using Date = "+date.getTime());
System.out.println("Current time in milliseconds using Calendar = "+cal.getTimeInMillis());
}
}
Output of the above program is:
上面程式的輸出是:
Current date using Date = Thu Nov 15 13:51:03 PST 2012
Current date using Calendar = Thu Nov 15 13:51:03 PST 2012
Current time in milliseconds using Date = 1353016263692
Current time in milliseconds using Calendar = 1353016263711
Few points to note while getting the current date in java:
在Java中擷取目前日期時要注意的幾點:
-
Calendar.getInstance() is more expensive method, so use it only when you need Calendar object. Else use Date object.
Calendar.getInstance()是更昂貴的方法,是以僅在需要Calendar對象時才使用它。 否則使用Date對象。
-
The number of milliseconds is the number of milliseconds since January 1, 1970, 00:00:00 GMT.
毫秒數是自格林威治标準時間1970年1月1日00:00:00以來的毫秒數。
-
Notice the difference between milliseconds in Calendar and Date object, it’s because of the time taken for java program to create Date and Calendar object. Date object is created first, hence it’s milliseconds value is lower.
請注意Calendar和Date對象中毫秒之間的差異,這是由于Java程式建立Date和Calendar對象所花費的時間。 首先建立日期對象,是以其毫秒值較低。
-
You can use SimpleDateFormat class to format the date in different ways.
您可以使用SimpleDateFormat類以不同方式設定日期格式。
Update: If you are working on Java 8, then you should consider using new Date Time API. For more details, please read Java Date Time API Tutorial.
更新 :如果您正在使用Java 8,則應考慮使用新的Date Time API。 有關更多詳細資訊,請閱讀Java Date Time API Tutorial 。
翻譯自: https://www.journaldev.com/703/get-current-date-time-java
java 擷取目前日期時間