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

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

问题描述

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

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 是包含您的 time 的对象)

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.

返回时区时间

不幸的是,我认为 SimpleDateFormat 将始终按本地时间格式化时间,因此我们不能再使用 SimpleDateFormat.所以要显示不同时区的时间,我们可以这样做

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 好得多(重量更轻、速度更快并提供更多功能).加上 JanuaryCalendar.Month0,这迫使开发者将 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天全站免登陆