Java 日历 ``isSet()`` 方法及示例


发布日期 : 2020-09-12 02:20:56 UTC

访问量: 10 次浏览

Calendar类中的 isSet(int calndr_field) 方法用于检查给定的日历字段是否有设定值。
所有通过内部字段的计算而设置了数值的Case都会通过 get() 方法的调用而被触发。

语法

public final boolean isSet(int calndr_field)

参数:该方法需要一个参数 calndr_field ,指的是要操作的日历字段。

返回值:如果日历字段的值被设置,该方法要么返回 true,要么返回 false

下面的程序说明了日历类的 isSet() 方法的工作。

示例

例1:

// Java code to illustrate
// isSet() method
   
import java.util.*;
public class CalendarDemo {
    public static void main(String args[])
    {
   
        // Creating a calendar object
        Calendar calndr = Calendar.getInstance();
   
        // Displaying the calendar object
        System.out.println("The Year is: "
                           + calndr.get(Calendar.YEAR));
   
        // Querying for the value if set or not
        boolean val = calndr.isSet(Calendar.YEAR);
        System.out.println("Is the"
                           + " Value set? " + val);
   
        // Clearing the instance
        calndr.clear(Calendar.YEAR);
   
        // Performing isSet() operation
        val = calndr.isSet(Calendar.YEAR);
        System.out.println("Is the"
                           + " Value set? " + val);
    }
}

输出

The Year is: 2019
Is the Value set? true
Is the Value set? false

例2:

// Java code to illustrate
// isSet() method
   
import java.util.*;
public class CalendarDemo {
    public static void main(String args[])
    {
   
        // Creating a calendar object
        Calendar calndr = Calendar.getInstance();
   
        // Displaying the calendar object
        System.out.println("Todays Day is: "
                           + calndr.get(
                                 Calendar.DAY_OF_MONTH));
   
        // Querying for the value if set or not
        boolean val
            = calndr.isSet(Calendar.DAY_OF_MONTH);
        System.out.println("Is the"
                           + " Value set? " + val);
   
        // Clearing the instance
        calndr.clear(Calendar.DAY_OF_MONTH);
   
        // Performing isSet() operation
        val = calndr.isSet(Calendar.DAY_OF_MONTH);
        System.out.println("Is the"
                           + " Value set? " + val);
    }
}

输出

Todays Day is: 21
Is the Value set? true
Is the Value set? false

参考资料:
https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#isSet-int-