How to initialize java.util.date to empty

后端 未结 5 1816
粉色の甜心
粉色の甜心 2021-01-04 02:12

I need your help in initializing a java.util.Date variable to empty. As I am running the page and it is showing NullPointerException if I didn\'t s

5条回答
  •  半阙折子戏
    2021-01-04 02:41

    Instance of java.util.Date stores a date. So how can you store nothing in it or have it empty? It can only store references to instances of java.util.Date. If you make it null means that it is not referring any instance of java.util.Date.

    You have tried date2=""; what you mean to do by this statement you want to reference the instance of String to a variable that is suppose to store java.util.Date. This is not possible as Java is Strongly Typed Language.

    Edit

    After seeing the comment posted to the answer of LastFreeNickname

    I am having a form that the date textbox should be by default blank in the textbox, however while submitting the data if the user didn't enter anything, it should accept it

    I would suggest you could check if the textbox is empty. And if it is empty, then you could store default date in your variable or current date or may be assign it null as shown below:

    if(textBox.getText() == null || textBox.getText().equals(""){
        date2 = null; // For Null;
        // date2 = new Date(); For Current Date
        // date2 = new Date(0); For Default Date
    }
    

    Also I can assume since you are asking user to enter a date in a TextBox, you are using a DateFormat to parse the text that is entered in the TextBox. If this is the case you could simply call the dateFormat.parse() which throws a ParseException if the format in which the date was written is incorrect or is empty string. Here in the catch block you could put the above statements as show below:

    try{
        date2 = dateFormat.parse(textBox.getText());
    }catch(ParseException e){
        date2 = null; // For Null;
        // date2 = new Date(); For Current Date
        // date2 = new Date(0); For Default Date
    }
    

提交回复
热议问题