Java DateFormat setLenient()方法及示例
DateFormat类中 的 setLenient(boolean leniency) 方法用于指定该DateFormat对象的日期和时间的解释是否宽松。
语法
public void setLenient(boolean leniency)
参数: 该方法需要一个布尔类型的参数leniency,指的是DateFormat对象的日历模式。布尔值true打开宽大模式,false关闭宽大模式。
返回值: 该方法不返回任何值。
下面的程序说明了日历类的setLenient()方法的工作情况:
例1 :
// Java code to illustrate// setLenient() method import java.text.*;import java.util.*; public class DateFormat_Demo { public static void main(String[] args) { // Initializing the first formatter DateFormat DFormat = DateFormat.getDateTimeInstance(); System.out.println("Object: " + DFormat); // String formatting String str = DFormat.format(new Date()); // Displaying the string time System.out.println(str); System.out.println("Leniency: " + DFormat.isLenient()); // Changing the leniency DFormat.setLenient(false); // Displaying the modified leniency System.out.println("New Leniency: " + DFormat.isLenient()); }}
输出:
Object: java.text.SimpleDateFormat@7945516eMar 28, 2019 6:03:48 PMLeniency: trueNew Leniency: false
例2 :
// Java code to illustrate// setLenient() method import java.text.*;import java.util.*; public class DateFormat_Demo { public static void main(String[] args) { // Initializing the first formatter DateFormat DFormat = DateFormat.getDateInstance(); System.out.println("Object: " + DFormat); // String formatting String str = DFormat.format(new Date()); // Displaying the string time System.out.println(str); System.out.println("Leniency: " + DFormat.isLenient()); // Changing the leniency DFormat.setLenient(false); // Displaying the modified leniency System.out.println("New Leniency: " + DFormat.isLenient()); }}输出:
Object: java.text.SimpleDateFormat@ce9bf0a5Mar 28, 2019Leniency: trueNew Leniency: false
参考资料: https://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#setLenient(布尔值)
