How to validate Date object in Java

好久不见. 提交于 2021-01-29 04:25:32

问题


Can any one tell me solution for the following: I have 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


回答1:


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);



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/3254075/how-to-validate-date-object-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!