Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform currentTimeMillis to a readable date format? [duplicate]

I want to use currentTimeMillis twice so I can calculate a duration but I also want to display Time and Date in user readable format. I'm having trouble as currentTimeMillis is good for the calculation but I can't see a built in function to convert to nice time or time/date.

I use

android.text.format.DateFormat df = new android.text.format.DateFormat(); df.format("yyyy-MM-dd kk:mm:ss", new java.util.Date()); 

for producing nice time and date and what I'd ultimately like to do is show my resulting currentTimeMillis value into the android.text.format.DateFormat df = new android.text.format.DateFormat();

e.g.

android.text.format.DateFormat df = currentTimeMillis(); 

when I try I get

Type mismatch: cannot convert from long to DateFormat

I've tried to use some casting but can't see how to accomplish this.

like image 458
Purplemonkey Avatar asked Apr 28 '12 14:04

Purplemonkey


People also ask

How do you convert milliseconds to date format?

Use the Date() constructor to convert milliseconds to a date, e.g. const date = new Date(timestamp) . The Date() constructor takes an integer value that represents the number of milliseconds since January 1, 1970, 00:00:00 UTC and returns a Date object.

How do I get time from system currentTimeMillis?

currentTimeMillis() method returns the current time in milliseconds. The unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.


2 Answers

It will work.

long yourmilliseconds = System.currentTimeMillis(); SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");     Date resultdate = new Date(yourmilliseconds); System.out.println(sdf.format(resultdate)); 
like image 118
asish Avatar answered Sep 19 '22 22:09

asish


There is a simpler way in Android

 DateFormat.getInstance().format(currentTimeMillis); 

Moreover, Date is deprecated, so use DateFormat class.

   DateFormat.getDateInstance().format(new Date(0));      DateFormat.getDateTimeInstance().format(new Date(0));      DateFormat.getTimeInstance().format(new Date(0));   

The above three lines will give:

Dec 31, 1969   Dec 31, 1969 4:00:00 PM   4:00:00 PM  12:00:00 AM 
like image 44
amalBit Avatar answered Sep 21 '22 22:09

amalBit