Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Unix time into readable Date in Java

Tags:

java

datetime

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

like image 312
SeanPONeil Avatar asked Nov 08 '11 05:11

SeanPONeil


1 Answers

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();
    }
like image 199
zeeshan Avatar answered Oct 07 '22 17:10

zeeshan