1

I have a location object to which I'm assigning the result of the getLastKnownLocation() method.

Now I need to know the age of these coordinates, in order to set a reasonable time frame in which I can update the latitude and longitude. I'm using Location.getTime() to get this value. However, I'm confused as to how exactly I should go about converting this value into hour. I need to update the location coordinates every X hours, hence the reason I need the value of getTime() in hours.

ayyyeee
  • 323
  • 1
  • 2
  • 6

3 Answers3

2

I have tried with Calendar but gives the wrong date. Below code is working fine.

Date date = new Date(location.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
return sdf.format(date);
Arul Pandian
  • 1,685
  • 15
  • 20
1

That's the UNIX epoch time. You can turn it into a date with Date date = new Date(location.getTime()).

You can also use Android's Calendar class:

Calendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(location.getTime());
int hour = calendar.get(Calendar.HOUR_OF_DAY);
jlhonora
  • 10,179
  • 10
  • 46
  • 70
0

Don't try to extract the hour from the timestamp, convert to Date and add X hours:

Date d = new Date(location.getTime());

Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.add(Calendar.HOUR, X);

Then get the time for the update with:

calendar.getTime();
lalibi
  • 3,057
  • 3
  • 33
  • 41