开发者

How to validate Date object in Java

开发者 https://www.devze.com 2023-01-07 15:14 出处:网络
Can any one tell me solution for the following: I hav开发者_StackOverflowe a Util.Date object in java.I want to validate the date entered. I am parsing the date object using the required format.

Can any one tell me solution for the following: I hav开发者_StackOverflowe a Util.Date object in java.I want to validate the date entered. I am parsing the date object using the required format.

For ex, Format is "MM/dd/yyyy" and Date entered is "23/12/2010" For this date, I am not getting any Parse Exception but the date is adjusted to "11/12/2011" which should not happen in my case.Instead I want to throw error message.

Please help me in this asap.

Thanks in advance


In DateFormat class you have to reset "lenient" flag, i.e.

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
sdf.setLenient(false);
. . .
sdf.parse(mydate, pos);


You must set your "lenient" mode of the SimpleDateFormat to false:

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
sdf.setLenient(false);

By default it is tolerant to some errors, and tries to interpret them somehow.


Depending upon your format expression , we can adjust month, date and year using SimpleDateFormat , code is below

public class SimpleDateFormatString2DateParse {

public static void main(String[] args) {

    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");

    try {
        Date date = formatter.parse("11/12/2011");
        System.out.println("Date is : " + date);

    } catch (Exception e) {
        e.printStackTrace();
    }

   }
   }

-----output-----

Date is : Sat Nov 12 00:00:00 PST 2011

0

精彩评论

暂无评论...
验证码 换一张
取 消