当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Calendar setTime()用法及代码示例


Calendar类中的setTime(Date dt)方法用于设置此Calendar的时间值表示的Calendars时间,并以给定或通过的日期为参数。

用法:

public final void setTime(Date dt))

参数:该方法采用Date类型的一个参数dt表示要设置的给定日期。


返回值:该方法不返回任何值。

以下示例程序旨在说明Calendar类的setTime()方法的用法:
示例1:

// Java code to illustrate 
// setTime() method 
  
import java.util.*; 
public class Calendar_Demo 
    extends GregorianCalendar { 
    public static void main(String[] args) 
    { 
        // Creating calendar objects 
        Calendar calndr1 
            = (Calendar)Calendar.getInstance(); 
        Calendar calndr2 
            = (Calendar)Calendar.getInstance(); 
  
        // Displaying the current date 
        System.out.println("The Current"
                           + " System Date: "
                           + calndr1.getTime()); 
  
        // Setting to a different date 
        calndr1.set(Calendar.MONTH, 5); 
        calndr1.set(Calendar.YEAR, 2006); 
        calndr1.set(Calendar.DAY_OF_WEEK, 15); 
        Date dt = calndr1.getTime(); 
  
        // Setting the timevalue 
        calndr2.setTime(dt); 
  
        // Displaying the new date 
        System.out.println("The modified"
                           + " Date:"
                           + calndr2.getTime()); 
    } 
}
输出:
The Current System Date: Fri Feb 22 07:33:13 UTC 2019
The modified Date:Sun Jun 18 07:33:13 UTC 2006

示例2:

// Java code to illustrate 
// setTime() method 
  
import java.util.*; 
  
public class Calendar_Demo 
    extends GregorianCalendar { 
  
    public static void main(String[] args) 
    { 
        // Creating calendar objects 
        Calendar calndr1 
            = (Calendar)Calendar.getInstance(); 
        Calendar calndr2 
            = (Calendar)Calendar.getInstance(); 
  
        // Displaying the current date 
        System.out.println("The Current"
                           + " System Date: "
                           + calndr1.getTime()); 
  
        // Setting to a different date 
        calndr1.set(Calendar.MONTH, 10); 
        calndr1.set(Calendar.YEAR, 1995); 
        calndr1.set(Calendar.DAY_OF_WEEK, 20); 
        Date dt = calndr1.getTime(); 
  
        // Setting the timevalue 
        calndr2.setTime(dt); 
  
        // Displaying the new date 
        System.out.println("The modified"
                           + " Date: "
                           + calndr2.getTime()); 
    } 
}
输出:
The Current System Date: Fri Feb 22 07:33:20 UTC 2019
The modified Date: Fri Nov 24 07:33:20 UTC 1995

参考: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#setTime(java.util.Date)



相关用法


注:本文由纯净天空筛选整理自Chinmoy Lenka大神的英文原创作品 Calendar setTime() Method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。