简体   繁体   中英

Convert Unix time into readable Date in Java

What is the easiest way to do this in Java? Ideally I will be using Unix time in milliseconds as input and the function will output a String like

November 7th, 2011 at 5:00 PM

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.

The above answered helped me for my Android app code. 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. 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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM