Primefaces日历组件&日期转换 [英] Primefaces Calendar component & date conversions
问题描述
我正在使用primefaces的日历组件.我在VO中有一个对应的字符串.在数据库中保存时,我需要将字符串转换为java.sql.date.
I am using primefaces' calendar component. I have a corresponding string in VO. While saving in database, I need to convert the string to java.sql.date.
xhtml :
<p:calendar value="#{articlePromo.startDate}"
id="vendorStartDateInputTxt" pattern="dd/MM/yyyy" mode="popup" showOn="button">
<f:convertDateTime type="date" dateStyle="short" pattern="dd/MM/yyyy" />
</p:calendar>
startDate(字符串)的值是:IST 2012年4月21日星期六5:30:00
The startDate (String) has the value : Sat Apr 21 05:30:00 IST 2012
获取sql日期的Java方法
public static Date getSQLDate(String strDate) {
java.sql.Date sqlDate = null;
try {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date dt = formatter.parse(strDate);
sqlDate = new java.sql.Date(dt.getTime());
} catch (Exception e) {
e.printStackTrace();
}
return sqlDate;
}
在转换日历的java.util.date时,我使用了dd/MM/yyyy模式.但转换日期为:IST 2012年4月21日星期六05:30:00.
While converting java.util.date of calendar, I used the pattern dd/MM/yyyy. But the date it got converted to is: Sat Apr 21 05:30:00 IST 2012.
- 上面写的 f:convertDateTime 标签有什么不正确的地方.
- 如果没有,我如何将该字符串转换为sql date.无法理解应该使用哪种格式.
- Is anything incorrect with f:convertDateTime tag written above.
- If not, how can I convert this string to sql date. Not able to understand what format should be given.
谢谢, 什卡(Shikha)
Thanks, Shikha
推荐答案
f:convertDateTime
仅将 String 转换为 Object ,反之亦然. p:calendar
的 Object 必须是java.util.Date
(它是value
属性). String 是您在浏览器中看到的格式化日期!
The f:convertDateTime
only converts String to Object and vice versa. The Object for the p:calendar
needs to be a java.util.Date
(it is the value
attribute). The String is the formatted date that you see in the browser!
Primefaces日历会自动附加一个转换器.这就是为什么在p:calendar
中具有pattern
属性的原因.
The Primefaces calendar automatically attaches a converter. That's why you have the pattern
attribute in p:calendar
.
因此,您应该删除丹尼尔已经建议的其他f:convertDateTime
.
So you should remove your additional f:convertDateTime
as already proposed by Daniel.
然后从java.util.Date
到java.sql.Date
的转换非常简单:
Then the conversion from java.util.Date
to java.sql.Date
is quite simple:
public java.sql.Date sqlDate(java.util.Date calendarDate) {
return new java.sql.Date(calendarDate.getTime());
}
这篇关于Primefaces日历组件&日期转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!