7

So below there's a simple way to get a readout from current time millis, but how do I get from my millisecond value to a readable time? Would I be just a stack of modulus that are dividing incrementally by 60? (exception being 100 milliseconds to a second)

Would I be right in thinking/doing that?

Thanks in advance for any help you can give

  public class DisplayTime {
    public static void main(String[] args) {
                System.out.print("Current time in milliseconds = ");
                System.out.println(System.currentTimeMillis());


        }
    }
user2802221
  • 71
  • 1
  • 1
  • 2
  • That gives you a `long` value. Use it with `java.util.Calendar`, by setting the time in milliseconds. Also then use a `DateFormat` to print it the way you want. – Sotirios Delimanolis Sep 21 '13 at 14:23
  • The usual knee-jerk-reflex answer has always been "use the Joda Time library." I'm surprised I don't see it yet. – scottb Sep 21 '13 at 14:31

3 Answers3

12

You may try like this:-

    long yourmilliseconds = 1119193190;
    SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");

    Date resultdate = new Date(yourmilliseconds);
    System.out.println(sdf.format(resultdate));
Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
3

Use that value with a Calendar object

Calendar c = Calendar.getInstance();
c.setTimeInMillis(System.currentTimeMillis());

String date = c.get(Calendar.YEAR)+"-"+c.get(Calendar.MONTH)+"-"+c.get(Calendar.DAY_OF_MONTH);
String time = c.get(Calendar.HOUR_OF_DAY)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND);

System.out.println(date + " " + time);

Output:

2013-8-21 16:27:31

Note: c.getInstance() already holds the current datetime, so the second line is redundant. I added it to show how to set the time in millis to the Calendar object

BackSlash
  • 21,927
  • 22
  • 96
  • 136
  • Maybe worth noting that the second line is redundant - getInstance already returns the current time. – assylias Sep 21 '13 at 14:28
  • @assylias Yes but the OP wants to transform that long in a readable date, so the second line shows how to do it. I will update my answer – BackSlash Sep 21 '13 at 14:29
3
System.out.println(new java.util.Date()); 

is the same as

System.out.println(new java.util.Date(System.currentTimeMillis()));

bothe represent the current time in a readable format

Ahmed Adel Ismail
  • 2,168
  • 16
  • 23