简体   繁体   English

在java.util.Date类型中插入特殊字符

[英]Insert special characters in java.util.Date type

In this invprbm.setFollowUpDate() is java.util.Date type. 在这个invprbm.setFollowUpDate()java.util.Date类型。
If the given value is empty, I have to set followUpDate as special characters - - , eg: 如果给定值为空,则必须将followUpDate设置为特殊字符- - ,例如:

SimpleDateFormat formatter = new SimpleDateFormat("- -");
invprbm.setFollowUpDate(formatter.parse("- -"));

In this scenario I am getting a value like Thu Jan 01 00:00:00 IST 1970 instead of the expected - - . 在这种情况下,我得到的值是Thu Jan 01 00:00:00 IST 1970而不是预期的- -

You seem to be asking how you should parse an "empty" date that you have denoted by the string "- -". 您似乎在问应该如何解析由字符串“--”表示的“空”日期。 And the simple answer is that you don't parse it! 简单的答案是您不解析它!

Instead do something like this: 而是这样做:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yy"); // or whatever
if (str.equals("- -")) {
    invprbm.setFollowupDate(null);
} else {
    invprbm.setFollowUpDate(formatter.parse(str));
}

And if you actually want to go from a Date to a String, you do it something like this: 而且,如果您实际上想要从日期转换为字符串,则可以执行以下操作:

if (date == null) {
    invprbm.setFollowupDate("- -");
} else {
    invprbm.setFollowUpDate(formatter.format(date));
}

The problem with your current approach is that SimpleDateFormat is not designed to cope with null Dates. 当前方法的问题是SimpleDateFormat不能用于处理null Date。 It can't parse a string to produce a null Date object, and it can't format a null Date object. 它不能解析字符串以产生一个null Date对象,也不能格式化一个null Date对象。

What your current code is actually doing is specifying a format that doesn't tell the parser how to extract any components of a date / time from the input string. 您当前的代码实际正在执行的操作是指定一种格式,该格式不会告诉解析器如何从输入字符串中提取日期/时间的任何成分。 The parse method is returning a Date object whose getTime() value is zero. parse方法返回的Date对象的getTime()值为零。 This is not unreasonable, since what you are trying to do falls outside of the javadoc specification for the SimpleDateFormat class. 这不是不合理的,因为您要尝试的操作超出了SimpleDateFormat类的javadoc规范。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM