且构网

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

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

更新时间:2023-01-27 23:40:31

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