如何将java.util.date初始化为空 [英] How to initialize java.util.date to empty

查看:1848
本文介绍了如何将java.util.date初始化为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要你的帮助才能将java.util.Date变量初始化为空。当我正在运行页面时,如果我没有选择任何日期,则显示nullpointerexception。

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 select any date.

代码为:

private java.util.Date date2;

我试图将该变量设为空,但它不起作用>

I tried to make that variable empty, but it didn't work>

private java.util.Date date2;

if (date2==null || date2.equals(""))
date2="";

然而,初始化时:

 private java.util.Date date2= new java.util.Date(0,0,0);

上面的代码会给我一个我不想要的默认值。

The above code will give me a default value which I don't want it.

推荐答案

java.util.Date 的实例存储日期。那么如何在其中存储任何内容或将其清空?它只能存储对 java.util.Date 实例的引用。如果你使它 null 意味着它没有引用任何 java.util.Date 的实例。

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.

您已尝试过 date2 =; 您希望引用该实例的此语句的意思 String 到一个假设存储 java.util.Date 的变量。这是不可能的,因为Java是强类型语言

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.

编辑

看到 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

我建议您检查文本框是否为空。如果它是空的,那么你可以在你的变量或当前日期存储默认日期,或者可以分配它 null ,如下所示:

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
}

此外我可以假设,因为您要求用户在 TextBox 中输入日期,正在使用 DateFormat 来解析在 TextBox 中输入的文本。如果是这种情况,您只需调用 dateFormat.parse()如果写入日期的格式不正确或为空,则会抛出 ParseException catch 块中你可以把上面的语句如下所示:

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
}

这篇关于如何将java.util.date初始化为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆