[英]Convert Unix time into readable Date in Java
What is the easiest way to do this in Java? 在Java中最简单的方法是什么? Ideally I will be using Unix time in milliseconds as input and the function will output a String like 理想情况下,我将以毫秒为单位使用Unix时间作为输入,函数将输出类似于的字符串
November 7th, 2011 at 5:00 PM 2011年11月7日下午5:00
SimpleDateFormat sdf = new SimpleDateFormat("MMMM d, yyyy 'at' h:mm a");
String date = sdf.format(myTimestamp);
I wanted to convert my unix_timestamps like 1372493313 to human readable format like Jun 29 4:08. 我想将我的unix_timestamps(如1372493313)转换为人类可读格式,如Jun 29 4:08。
The above answered helped me for my Android app code. 以上回答帮助我获得了我的Android应用程序代码。 A little difference was that on Android it recommends to use locale settings as well, and my original unix_timestamp was in seconds, not milliseconds, and Eclipse wanted to add try/catch block or throw exception. 有点不同的是,在Android上它建议使用区域设置,而我原来的unix_timestamp是以秒为单位,而不是毫秒,Eclipse想要添加try / catch块或抛出异常。 So my working code has to be modified a bit like this: 所以我的工作代码必须修改如下:
/**
*
* @param unix_timestamp
* @return
* @throws ParseException
*/
private String unixToDate(String unix_timestamp) throws ParseException {
long timestamp = Long.parseLong(unix_timestamp) * 1000;
SimpleDateFormat sdf = new SimpleDateFormat("MMM d H:mm", Locale.CANADA);
String date = sdf.format(timestamp);
return date.toString();
}
And here is the calling code: 这是调用代码:
String formatted_timestamp;
try {
formatted_timestamp = unixToDate(unix_timestamp); // timestamp in seconds
} catch (ParseException e) {
e.printStackTrace();
}
java.util.Date date = new java.util.Date((long) time * 1000L);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.