Java – converts the timestamp length to the normal date format
In my network application, the time of some activities of the user is stored as a timestamp in the database (in the database) and displayed back to the user, which needs to be converted to the normal date / time format
(in fact, my database Cassandra stores the length value of a column written to the timestamp (microseconds since 1970), which I will use to find the corresponding user activity time)
I am using JSF 2.0 (keyboard), and I believe there is a converter that may help this conversion? Otherwise, how can we maximize these transformations?
Solution
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 an object containing your time)
<h:dataTable value="#{myBean.convertTime(myBean.foo.time)}" />
If you have multiple pages to use this method, you can put it in an abstract class and have your managed bean extend this abstract class
Editing: using timezone to return time
Unfortunately, I think simpledateformat will always format the local time, so we can use simpledateformat So to display time in different time zones, 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 take advantage of jodatime In my opinion, this API is better than calendar (lighter, faster and provides more functions) Add calendar Month is 0 in January, forcing developers to add 1 results. You must format the time yourself With jodatime, you can fix all of these Correct me if I'm wrong, but I think jodatime was incorporated into JDK7