
“嗨,阿米戈。我想告訴你一個有趣的類型,叫做日期。這個類型存儲日期和時間,還可以測量時間間隔。”
“聽起來很有趣,請繼續。”
“每個 Date 對像都以一種相當有趣的形式存儲時間:自 1970 年 1 月 1 日以來的毫秒數,格林威治標準時間。”
“哇!”
“是的。這個數字太大了,在 int 中沒有足夠的空間容納它,所以它必須存儲在 long 中。但這對於計算任意兩個日期之間的差異非常方便。你只需做減法來找出差異精確到毫秒。它還解決了日期變更線和夏令時的問題。”
“最有趣的部分是每個對像在創建時都用當前時間初始化。要知道當前時間,您只需要創建一個 Date 對象。”
“你如何使用它?”
“這裡有些例子:”
獲取當前日期:
public static void main(String[] args) throws Exception
{
Date today = new Date();
System.out.println("Current date: " + today);
}
計算兩個日期之間的差異
public static void main(String[] args) throws Exception
{
Date currentTime = new Date(); // Get the current date and time
Thread.sleep(3000); // Wait 3 seconds (3000 milliseconds)
Date newTime = new Date(); // Get the new current time
long msDelay = newTime.getTime() - currentTime.getTime(); // Calculate the difference
System.out.println("Time difference is: " + msDelay + " in ms");
}
檢查是否經過了一定的時間:
public static void main(String[] args) throws Exception
{
Date startTime = new Date();
long endTime = startTime.getTime() + 5000; // +5 seconds
Date endDate = new Date(endTime);
Thread.sleep(3000); // Wait 3 seconds
Date currentTime = new Date();
if(currentTime.after(endDate))// Check whether currentTime is after endDate
{
System.out.println("End time!");
}
}
確定自一天開始以來經過了多少時間:
public static void main(String[] args) throws Exception
{
Date currentTime = new Date();
int hours = currentTime.getHours();
int mins = currentTime.getMinutes();
int secs = currentTime.getSeconds();
System.out.println("Time since midnight " + hours + ":" + mins + ":" + secs);
}
確定自年初以來已經過去了多少天:
public static void main(String[] args) throws Exception
{
Date yearStartTime = new Date();
yearStartTime.setHours(0);
yearStartTime.setMinutes(0);
yearStartTime.setSeconds(0);
yearStartTime.setDate(1); // First day of the month
yearStartTime.setMonth(0); // January (the months are indexed from 0 to 11)
Date currentTime = new Date();
long msTimeDifference = currentTime.getTime() - yearStartTime.getTime();
long msDay = 24 * 60 * 60 * 1000; // The number of milliseconds in 24 hours
int dayCount = (int) (msTimeDifference/msDay); // The number of full days
System.out.println("Days since the start of the year: " + dayCount);
}
“該getTime()
方法返回存儲在 Date 對像中的毫秒數。”
“該after()
方法檢查我們調用該方法的日期是否在傳遞給該方法的日期之後。”
“這些getHours(), getMinutes(), getSeconds()
方法分別返回調用它們的對象的小時數、分鐘數和秒數。”
“此外,在最後一個示例中,您可以看到可以更改存儲在Date對像中的日期/時間。我們獲取當前時間和日期,然後將小時、分鐘和秒重置為 0。我們還將 January 設置為月和 1 作為該月的第幾天。因此,該yearStartTime
對象存儲當前年份的 1 月 1 日和時間 00:00:00。”
“之後,我們再次獲取當前日期 ( currentTime
),以毫秒為單位計算兩個日期之間的差異,並將其存儲在 中msTimeDifference
。”
“然後我們除以msTimeDifference
24 小時內的毫秒數,得到從當年年初到今天的整天數。”
“哇!這太酷了!”
GO TO FULL VERSION