将时间戳转换为正常日期格式 [英] Convert timestamp long to normal date format

查看:2024
本文介绍了将时间戳转换为正常日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的网络应用中,日期&用户特定活动的时间存储(在数据库中)作为时间戳显示回用户需要转换为正常的日期/时间格式。

In my web app, date & time of a user's certain activity is stored(in database) as a timestamp Long which on being displayed back to user needs to be converted into normal date/time format.

(实际上我的数据库Cassandra存储了一个列写入时的时间戳,作为一个长值(自1970年以来的微秒),我将用它来查找超出相应用户活动的时间)

我使用的是JSF 2.0(+ primefaces),我认为它有可能对这种转换有帮助的转换器?或者我怎样才能充其量实现这些转换呢?

I am using JSF 2.0(+ primefaces) which I believe has converters that may be helpful for this conversion? Or otherwise how How can I, at best, achieve these conversions?

推荐答案

让我为您提出这个解决方案。所以在你的托管bean中,这样做

Let me propose this solution for you. So in your managed bean, do this

public String convertTime(long time){
    Date date = new Date(time);
    Format format = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
    return format.format(date);
}

所以在你的JSF页面中,你可以这样做(假设 foo 是包含时间的对象

so in your JSF page, you can do this (assuming foo is the object that contain your time)

<h:dataTable value="#{myBean.convertTime(myBean.foo.time)}" />

如果您有多个页面想要使用此方法,可以将其放入抽象类并让您的托管bean扩展此抽象类

If you have multiple pages that want to utilize this method, you can put this in an abstract class and have your managed bean extend this abstract class.

编辑:使用TimeZone返回时间

不幸的是,我认为 SimpleDateFormat 将始终以当地时间格式化时间,因此我们不能再使用 SimpleDateFormat 了。因此,要在不同的TimeZone中显示时间,我们可以这样做

unfortunately, I think SimpleDateFormat will always format the time in local time, so we can't use SimpleDateFormat anymore. So to display time in different TimeZone, we can do this

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));

}

更好的解决方案是使用 JodaTime 。在我看来,这个API比Calendar更好(重量更轻,速度更快,功能更多)。加 Calendar.Month 1月 0 ,那个力量开发人员将 1 添加到结果中,您必须自己格式化时间。使用 JodaTime ,您可以解决所有这些问题。如果我错了,请纠正我,但我认为 JodaTime 包含在 JDK7

A better solution is to utilize JodaTime. In my opinion, this API is much better than Calendar (lighter weight, faster and provide more functionality). Plus Calendar.Month of January is 0, that force developer to add 1 to the result, and you have to format the time yourself. Using JodaTime, you can fix all of that. Correct me if I am wrong, but I think JodaTime is incorporated in JDK7

这篇关于将时间戳转换为正常日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆