Raj*_*pta 18 java jsf primefaces
在我的Web应用程序中,用户的某些活动的日期和时间被存储(在数据库中)作为时间戳Long
,其被显示回用户需要被转换为正常的日期/时间格式.
(实际上我的数据库Cassandra存储了列写入时的时间戳,作为一个长值(自1970年以来的微秒),我将用它来查找相应用户活动的时间)
我正在使用JSF 2.0(+ primefaces),我认为它有可能对此转换有帮助的转换器?或者我怎样才能充其量实现这些转换呢?
Tha*_*ham 59
让我为您提出这个解决方案.所以在你的托管bean中,做到这一点
public String convertTime(long time){
Date date = new Date(time);
Format format = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
return format.format(date);
}
Run Code Online (Sandbox Code Playgroud)
所以在你的JSF页面中,你可以这样做(假设foo
是包含你的对象time
)
<h:dataTable value="#{myBean.convertTime(myBean.foo.time)}" />
Run Code Online (Sandbox Code Playgroud)
如果您有多个页面想要使用此方法,您可以将其放入abstract class
并让托管bean扩展它abstract class
.
编辑:使用TimeZone返回时间
不幸的是,我认为SimpleDateFormat
总会在当地时间格式化时间,所以我们不能再使用SimpleDateFormat
了.因此,要在不同的TimeZone中显示时间,我们可以这样做
public String convertTimeWithTimeZome(long time){
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
cal.setTimeInMillis(time);
return (cal.get(Calendar.YEAR) + " " + (cal.get(Calendar.MONTH) + 1) + " "
+ cal.get(Calendar.DAY_OF_MONTH) + " " + cal.get(Calendar.HOUR_OF_DAY) + ":"
+ cal.get(Calendar.MINUTE));
}
Run Code Online (Sandbox Code Playgroud)
更好的解决方案是利用JodaTime
.在我看来,这个API比Calendar更好(重量更轻,速度更快,功能更多).加Calendar.Month
的January
就是0
,这种力量开发人员添加1
到结果,你必须自己格式化时间.使用JodaTime
,您可以解决所有这些问题.如果我错了,请纠正我,但我认为JodaTime
已纳入JDK7
归档时间: |
|
查看次数: |
98818 次 |
最近记录: |