Convert timestamp long to normal date format

前端 未结 5 1455
南旧
南旧 2020-12-09 03:46

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 conver

5条回答
  •  孤街浪徒
    2020-12-09 04:25

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

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

    
    

    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.

    EDIT: Return time with 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));
    
    }
    

    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

提交回复
热议问题