import java.text.*;
public class DateUtils {
public static boolean isValidDateStr(String date) {
try {
DateFormat df =
DateFormat.getDateInstance
(DateFormat.SHORT); // YYYY-MM-DD
df.setLenient(false); // this is important!
df.parse(date);
}
catch (ParseException e) {
return false;
}
catch (IllegalArgumentException e) {
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(" 1900-12-13 valid ? "
+ DateUtils.isValidDateStr("1900-12-13"));
// "1990-12/13" throws a ParseException
System.out.println(" 1900-12/13 valid ? "
+ DateUtils.isValidDateStr("1900-12/13"));
// "1990-13-12" throws a IllegalArgumentException
System.out.println(" 1900-13-12 valid ? "
+ DateUtils.isValidDateStr("1900-13-12"));
/*
* output :
* 1900-12-13 valid ? true
* 1900-12/13 valid ? false
* 1900-13-12 valid ? false
*/
}
}
package com.rgagnon.howto;
import java.text.*;
public class DateUtils {
public static boolean isValidDateStr(String date, String format) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setLenient(false);
sdf.parse(date);
}
catch (ParseException e) {
return false;
}
catch (IllegalArgumentException e) {
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(" 1900-12-13 valid ? "
+ DateUtils.isValidDateStr("1900-12-13","yyyy-MM-dd"));
// "1990-12/13" throws a ParseException
System.out.println(" 1900-12/13 valid ? "
+ DateUtils.isValidDateStr("1900-12/13","yyyy-MM-dd"));
// "1990-13-12" throws a IllegalArgumentException
System.out.println(" 1900-13-12 valid ? "
+ DateUtils.isValidDateStr("1900-13-12","yyyy-MM-dd"));
/*
* output :
* 1900-12-13 valid ? true
* 1900-12/13 valid ? false
* 1900-13-12 valid ? false
*/
}
}
import java.util.*;
public class jtest {
public static void main(String args[]) {
try {
GregorianCalendar gc = new GregorianCalendar();
gc.setLenient(false); // must do this
gc.set(GregorianCalendar.YEAR, 2003);
gc.set(GregorianCalendar.MONTH, 42);// invalid month
gc.set(GregorianCalendar.DATE, 1);
gc.getTime(); // exception thrown here
}
catch (Exception e) {
e.printStackTrace();
}
}
}Written and compiled by Réal Gagnon ©1998-2007
[ home ]