Java 无法将“0000-00-00 00:00:00”转换为时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1363527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot convert '0000-00-00 00:00:00' to TIMESTAMP
提问by Oleksandr
the field definition
字段定义
/** Date. */
@Column(columnDefinition = "datetime")
private Date date;
setter
二传手
public void setDate(final Date date) {
DateFormat dfmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
this.date = dfmt.parse(dfmt.format(date));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Does anyone have idea how to convert "zero date" into proper value ? Because i have error:
有谁知道如何将“零日期”转换为正确的值?因为我有错误:
Cannot convert value '0000-00-00 00:00:00' from column 13 to TIMESTAMP
And even if i set "default" field and setter like this:
即使我像这样设置“默认”字段和设置器:
/** Date. */
@Column
private Date date;
public void setDate(final Date date) {
this.date = date;
}
I'll still have the same problem....
我还是会遇到同样的问题......
采纳答案by ChssPly76
I'm going to take a wild guess here that you're using MySQL :-) It uses "zero dates" as special placeholder- unfortunatelly, JDBC can not handle them by default.
我将在这里大胆猜测您正在使用 MySQL :-) 它使用“零日期”作为特殊占位符- 不幸的是,JDBC 默认无法处理它们。
The solution is to specify "zeroDateTimeBehavior=convertToNull" as parameter to your MySQL connection (either in datasource URL or as an additional property), e.g.:
解决方案是将“zeroDateTimeBehavior=convertToNull”指定为 MySQL 连接的参数(在数据源 URL 中或作为附加属性),例如:
jdbc:mysql://localhost/myDatabase?zeroDateTimeBehavior=convertToNull
This will cause all such values to be retrieved as NULLs.
这将导致所有此类值都作为 NULL 检索。
回答by KLE
I don't understand the point in your code, where you format then parse again a date. This seems like an identical operation. Maybe you could elaborate?
我不明白您的代码中的要点,您格式化然后再次解析日期。这似乎是一个相同的操作。也许你可以详细说明?
If you want to give a default value to a date, you could do :
如果你想给一个日期一个默认值,你可以这样做:
/** Jan 1, 1970 ; first moment in time in Java */
private static final Date NO_DATE = new Date(0L);
private Date date;
public void setDate(final Date date) {
if (date == null) {
this.date = NO_DATE;
} else {
this.date = date;
}
}
Note : the annotation are optionnal, here I didn't add them.
注意:注释是可选的,这里我没有添加它们。
In this code, you could substitute what you want to the condition, and to the default value.
在此代码中,您可以将所需的内容替换为条件和默认值。
You could also add a similar setter, that would take a String argument, and check for your special "00000..." value. This would allow for setting the field either with a Date, or with a String.
您还可以添加一个类似的 setter,它将接受一个 String 参数,并检查您的特殊“00000...”值。这将允许使用日期或字符串设置字段。