java之使用postgreSQL的Mybatis日期对象问题
其实我不清楚这个问题是Java,JSP还是Mybatis。
目前面临的问题如下:
前端
Java JSP Struts 2 Spring
后端
PostgreSQL 9.3.XX
问题
在 PostgreSQL 中
birthday date;
在jsp页面中编写的代码
<sj:datepicker name="birthday" id="birthday"></sj:datepicker>
在 Java 文件中使用 mybatis 生成器生成以下代码
private Date birthday;
在 Mybatis 文件中
insert into "TABLE" (birthday) values (#{birthday, jdbcType=DATE});
当从 jsp 页面插入值时 [1988/01/13] 然后在 java 控制台中获取
[Sat Jun 11 00:00:00 JST 18] 值。这是错误的。
如果我将 private Date birthday 更改为 private String birthday 那么控制台没有任何问题,但在数据库中插入值会生成错误。
Error Code :42804
birthday is a date trying to insert character varying.
我尝试了不同的方法,但仍然没有找到答案。
如何在日期对象(而不是字符串)中获取 YYYY/MM/DD
格式?
请您参考如下方法:
Struts2 日期转换
对于日期,Struts2 uses the SHORT
format for the Locale
associated与当前请求。
这意味着如果您使用的是印度语言环境,则格式为 dd/MM/yy
,因此您可以安全地输入 13/01/1988
在 JSP 中并将其成功转换为 java.util.Date
Action 中的对象。
如果您使用的是美国语言环境,则格式为 MM/dd/yy
, 你需要插入 01/13/1988
否则它不会工作。
ISO8601 和 RFC3339
为了处理这类问题,多年前国际标准组织创建了 ISO 8601标准:
ISO 8601 Data elements and interchange formats – Information interchange – Representation of dates and times is an international standard covering the exchange of date and time-related data. It was issued by the International Organization for Standardization (ISO) and was first published in 1988. The purpose of this standard is to provide an unambiguous and well-defined method of representing dates and times, so as to avoid misinterpretation of numeric representations of dates and times, particularly when data are transferred between countries with different conventions for writing numeric dates and times.
ISO 8601 日期格式为 yyyy-MM-dd
,您正在使用的那个。
在 HTML5 生态系统(日期选择器等)中选择并采用了 ISO 8601 的特定配置文件,并在 RFC 3339 中进行了描述。 .
它在完整表示上略有不同,但仅日期格式是相同的 ( yyyy-MM-dd
)。
Struts2-jQuery-plugin 的 <sj:datepicker>
标记日期格式应该已经默认为 yy-MM-dd
, IIRC.
完成任务
以这种格式输入的日期自动转换has been recently introduced并且在 Struts 2.5(测试版)中可用。它也应该在下一个版本 (2.3.25+) 中发布。
否则,你需要create a converter像下面这样:
public class RFC3339Converter extends StrutsTypeConverter{
@Override
public String convertToString(Map context, Object o) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(o);
}
@Override
public Object convertFromString(Map context, String[] values, Class toClass) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
return (values[0].length()==0) ? null : (Date) sdf.parse(values[0]);
} catch (ParseException e) {
return values[0];
}
}
}
你知道吗?
浏览器(可能)具有 native 日期选择器,您可以将其优雅地降级为 javascript 日期选择器,as described in this answer .
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。