2

I'm using the Location class and the getTime() method to get the current time in Android. Then I'm sending that Long number to some other device. That device receives the Long number and should display the data in a message box, but I don't know how to convert it into DD:MM:YY and time of the day (or anything readable by a human, actually). How do I do this? I can't use the current format, it has to be something that the average user can read.

Thank you!

user1549053
  • 109
  • 3
  • 8
  • 1
    read documentation. seriously, please. – njzk2 Oct 05 '12 at 14:12
  • possible duplicate of [How do you format date and time in Android?](http://stackoverflow.com/questions/454315/how-do-you-format-date-and-time-in-android) – Sam Oct 05 '12 at 16:28
  • Thanks to everyone for quick answers, this site helped me a lot! I hope I can help someone else some day, when I learn enough to do that :D – user1549053 Oct 06 '12 at 00:10

3 Answers3

6

Assuming you don't want to use Joda Time (might be a bit big for an Android app) you should probably use a DateFormat such as SimpleDateFormat:

// See notes below
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date(location.getTime());
String formatted = format.format(date);

There are cultural issues you should consider though:

  • You may wish to explicitly set the locale, if you believe the default may not suit you
  • Rather than hard-code the format, you may want to use DateFormat.getDateTimeInstance()
  • You should consider which time zone you're interested in; presumably the user's time zone, which should be the default for any DateFormat you create, but perhaps something else...
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4

you do this by this way

long longD// as you receive in long format

Date d = new Date(longD);

SimpleDateFormat sdf = new SimpleDateFormat("dd:MM:yy");

String sDate = sdf.format(d);
Pratik
  • 30,639
  • 18
  • 84
  • 159
  • Could use this for time. SimpleDateFormat sf = new SimpleDateFormat("mm-dd-yyyy'T'HH:mm:ss"); – Philip Rego Jun 16 '14 at 05:54
  • 1
    @PhilipRego: Yes you can Could use this for time by specifying your time format. SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss"); – Pratik Jun 16 '14 at 07:53
0

From here: http://developer.android.com/reference/android/location/Location.html#getTime%28%29 you can see that the method getTime is returning the time in milliseconds from January 1, 1970.

This could maybe help on how to get the date format you need: Getting "unixtime" in Java

Community
  • 1
  • 1
Milos Cuculovic
  • 19,631
  • 51
  • 159
  • 265