2

I've tried to convert a UNIX Timestamp to todays date time.

Like I have a simple UNIX Timestamp and then I want to convert it like this:

Today at: theTimeFromMyTimestamp

Anyone that has a correct solution for this?

Thanks in advance!

Curtain
  • 1,972
  • 3
  • 30
  • 51

4 Answers4

7

Try this DateFormat.getDateFormat(mContext).format(new Date(myTimestamp * 1000))

As new Date() requires milliseconds instead of seconds, you have to multiple by 1000

WarrenFaith
  • 57,492
  • 25
  • 134
  • 150
  • 2
    Remember that myTimestamp needs to be a long integer, otherwise it will probably wrap around to negative when you multiply by 1000. – ben Oct 20 '12 at 10:35
4

You can also have a tighter control of the final format by making it explicit. It also avoids creating a Date object and needs no context:

DateFormat.format("dd/MM/yyyy hh:mm:ssaa", myTimeStamp * 1000L);
2

You need to convert the timestamp milisecond to long int by adding a L in the multiplication:

DateFormat.getDateFormat(mContext).format(new Date(myTimestamp * 1000L)) 
HighCommander4
  • 50,428
  • 24
  • 122
  • 194
Kamrul
  • 7,175
  • 3
  • 31
  • 31
1
/**
 * Get the human readable String representation of time
 * @param unix_time
 * @return String format of time eg 13:20
 * @throws NullPointerException
 * @throws IllegalArgumentException
 */
public String convertFromUnix(String unix_time) throws NullPointerException, IllegalArgumentException{
    long time = Long.valueOf(unix_time);
    String result = "";
    Date date = new Date(time);
    SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
    format.setTimeZone(TimeZone.getTimeZone("GMT"));
    result = format.format(date);
    Log.d("date", format.format(date));

    return result;
}
Robby Lebotha
  • 1,211
  • 11
  • 9