Java Calendar setTimeInMillis() 方法



描述

Java Calendar setTimeInMillis(long) 方法使用給定的長整型值設定日曆的當前時間。

宣告

以下是 java.util.Calendar.setTimeInMillis() 方法的宣告

public void setTimeInMillis(long millis)

引數

millis − 從紀元開始以毫秒為單位的新時間(UTC 時間)。

返回值

此方法不返回值。

異常

在當前日期的日曆例項中設定毫秒時間示例

以下示例演示了 Java Calendar setTimeInMillis() 方法的使用。我們使用 getInstance() 方法建立當前日期的日曆例項,並使用 getTime() 方法列印日期和時間。然後,我們使用 setTimeInMillis() 更新日期。最後,列印更新後的日期。

package com.tutorialspoint;

import java.util.Calendar;

public class CalendarDemo {
   public static void main(String[] args) {

      // create a calendar
      Calendar cal = Calendar.getInstance();

      // get the time
      System.out.println("Current time is :" + cal.getTime());

      // set time to 5000 ms after january 1 1970
      cal.setTimeInMillis(5000);

      // print the new time
      System.out.println("After setting Time:  " + cal.getTime());
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Current time is :Wed Sep 28 17:56:54 IST 2022
After setting Time:  Thu Jan 01 05:30:05 IST 1970

在當前日期的 GregorianCalendar 例項中設定毫秒時間示例

以下示例演示了 Java Calendar setTimeInMillis() 方法的使用。我們使用 GregorianCalendar() 方法建立當前日期的日曆例項,並使用 getTime() 方法列印日期和時間。然後,我們使用 setTimeInMillis() 設定日期進行更新。最後,列印更新後的日期。

package com.tutorialspoint;

import java.util.Calendar;
import java.util.GregorianCalendar;

public class CalendarDemo {
   public static void main(String[] args) {

      // create a calendar
      Calendar cal = new GregorianCalendar();

      // get the current time
      System.out.println("Current time is :" + cal.getTime());

      // set time to 5000 ms after january 1 1970
      cal.setTimeInMillis(5000);

      // print the new time
      System.out.println("After setting Time:  " + cal.getTime());
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Current time is :Wed Sep 28 17:59:23 IST 2022
After setting Time:  Thu Jan 01 05:30:05 IST 1970

在給定日期的 GregorianCalendar 例項中設定毫秒時間示例

以下示例演示了 Java Calendar setTimeInMillis() 方法的使用。我們使用 GregorianCalendar() 方法建立特定日期的日曆例項,並使用 getTime() 方法列印日期和時間。然後,我們使用 setTimeInMillis() 設定日期進行更新。最後,列印更新後的日期。

package com.tutorialspoint;

import java.util.Calendar;
import java.util.GregorianCalendar;

public class CalendarDemo {
   public static void main(String[] args) {

      // create a calendar
      Calendar cal = new GregorianCalendar(2022,8,27);

      // get the current time
      System.out.println("Current time is :" + cal.getTime());

      // set time to 5000 ms after january 1 1970
      cal.setTimeInMillis(5000);

      // print the new time
      System.out.println("After setting Time:  " + cal.getTime());
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Current time is :Tue Sep 27 00:00:00 IST 2022
After setting Time:  Thu Jan 01 05:30:05 IST 1970
java_util_calendar.htm
廣告