79

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.

Ajay Mistry
  • 951
  • 1
  • 14
  • 30
Purplemonkey
  • 1,927
  • 3
  • 27
  • 39

2 Answers2

187

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));
Bato-Bair Tsyrenov
  • 1,174
  • 3
  • 17
  • 40
asish
  • 4,767
  • 4
  • 29
  • 49
  • 1
    thanks thought there would be something, but its likely to be easier to find a pin in a haystack! cheers. – Purplemonkey Apr 28 '12 at 14:45
  • Thanks, was dealing with a pesky problem and tried solving on my own, making the date readable made it so much simpler to solve my problem. – Meenohara Feb 10 '21 at 18:08
48

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
amalBit
  • 12,041
  • 6
  • 77
  • 94