0

I have my code

DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

Date curDate = new Date();
String finalCurTime=format.format(curDate).substring(11, 19);

Date gpsLastDate = new Date(gpslastKnownLocation.getTime());
String gpsFinalLastTime=format.format(gpsLastDate).substring(11, 19);

How can i compare to below Logic

  • Compare finalCurTime & gpsFinalLastTime

If(If finalCurTime is more than three hours of gpsFinalLastTime)
{
// Do something-1
}else{
// Do something-2
} 
Devrath
  • 42,072
  • 54
  • 195
  • 297
  • Why are you looking at the *string* representations? – Jon Skeet Nov 11 '14 at 09:38
  • why are you not comparing date object directly using compareTo() ? – Haresh Chhelana Nov 11 '14 at 09:38
  • @Jon Skeet ... I taught this would be easier. How can I use date objects directly for my use case – Devrath Nov 11 '14 at 09:40
  • @HareshChhelana ...How can I use date objects directly for my use case, are there any existing Stackoverflow answers for this kind of scenario ? – Devrath Nov 11 '14 at 09:41
  • Look at `Date.getTime()`, which will return the number of milliseconds since the Unix epoch. Subtracting integers tends to be easier than subtracting strings :) – Jon Skeet Nov 11 '14 at 09:43
  • create a custom funtion in which you pass date as argument and it return the hours then compare hours it's the best way to do that – Danial Hussain Nov 11 '14 at 09:43
  • @Jon Skeet .... OK, any method where I can specify the threshold(difference) along with `Date.getTime()`. – Devrath Nov 11 '14 at 09:49
  • 2
    You don't. You perform normal arithmetic. Pretend we weren't talking about dates and times - if you had a `Person` API with an `int getSalary()` method, and you wanted to check whether one person's salary was (say) at least 5000 more than another's, what would you do? Figure that out, then apply it to the date/time domain. – Jon Skeet Nov 11 '14 at 09:51
  • @JonSkeet ... Got it .... so the result of `Date.getTime()` is shown in milliseconds so i just have to see the difference for three hours(in milli seconds). Thanks ! – Devrath Nov 11 '14 at 09:56
  • http://stackoverflow.com/questions/17940200/how-to-find-the-duration-of-difference-between-two-dates-in-java checkout this it may help you. – mady Nov 11 '14 at 10:00

2 Answers2

0

Use Date.getTime() to get the time in milliseconds.

// If the difference in milliseconds is larger than 3 hours in milliseconds
if (curDate.getTime() - gpsLastDate.getTime() > 10800000) {
    // Do something-1
} else {
    // Do something-2
} 
Harpunius
  • 120
  • 7
0
Calendar calendarobj = Calendar.getInstance();
calendarobj.setTime(gpsLastDate);
int hour = calendarobj.get(Calendar.HOUR);
if(hour>3)
    System.out.println("greater");
Mallieswari
  • 113
  • 9