且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将时间戳转换为正常日期格式

更新时间:2023-01-27 23:36:32

让我为您提出这个解决方案。所以在你的托管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