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!
Try this DateFormat.getDateFormat(mContext).format(new Date(myTimestamp * 1000))
As new Date()
requires milliseconds instead of seconds, you have to multiple by 1000
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);
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))
/**
* 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;
}