當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Date setTime()用法及代碼示例


Java Date類的setTime()方法設置日期對象。它將日期對象設置為代表格林尼治標準時間1970年1月1日00:00:00之後的時間毫秒。
用法:

public void setTime(long time)

參數:該函數接受單個參數時間,該時間指定毫秒數。

返回值:它方法沒有返回值。


異常:該函數不會引發任何異常。

下麵的程序演示了上述函數:

示例1:

// Java code to demonstrate 
// setTime() function of Date class 
  
import java.util.Date; 
import java.util.Calendar; 
public class GfG { 
    // main method 
    public static void main(String[] args) 
    { 
  
        // creating a date object with specified time. 
        Date dateOne = new Date(); 
  
        System.out.println("Date initially: "
                           + dateOne); 
  
        // Sets the time 
        dateOne.setTime(1000); 
  
        // Prints the time 
        System.out.println("Date after setting"
                           + " the time: "
                           + dateOne); 
    } 
}
輸出:
Date initially: Wed Jan 02 09:34:03 UTC 2019
Date after setting the time: Thu Jan 01 00:00:01 UTC 1970

示例2:

// Java code to demonstrate 
// setTime() function of Date class 
  
import java.util.Date; 
import java.util.Calendar; 
public class GfG { 
    // main method 
    public static void main(String[] args) 
    { 
  
        // creating a Calendar object 
        Calendar c1 = Calendar.getInstance(); 
  
        // set Month 
        // MONTH starts with 0 i.e. ( 0 - Jan) 
        c1.set(Calendar.MONTH, 11); 
  
        // set Date 
        c1.set(Calendar.DATE, 05); 
  
        // set Year 
        c1.set(Calendar.YEAR, 1996); 
  
        // creating a date object with specified time. 
        Date dateOne = c1.getTime(); 
  
        System.out.println("Date initially: "
                           + dateOne); 
  
        // Sets the time 
        dateOne.setTime(1000999); 
  
        // Prints the time 
        System.out.println("Date after setting"
                           + " the time: "
                           + dateOne); 
    } 
}
輸出:
Date initially: Thu Dec 05 09:32:53 UTC 1996
Date after setting the time: Thu Jan 01 00:16:40 UTC 1970


相關用法


注:本文由純淨天空篩選整理自Twinkl Bajaj大神的英文原創作品 Date setTime() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。