11

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

2

3 Answers 3

19
SimpleDateFormat sdf = new SimpleDateFormat("MMMM d, yyyy 'at' h:mm a"); String date = sdf.format(myTimestamp); 
Sign up to request clarification or add additional context in comments.

3 Comments

This works really well, except when the ends in a '0', such as 1:40 or 5:20, the 0 won't be displayed.
Sorry, try h:mm instead of h:m
I was getting jan 1970 as output when my timestamp was of jan 2015. Multiplying timestamp by 1000L does the trick.
4

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

Comments

0
java.util.Date date = new java.util.Date((long) time * 1000L); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.