1

In my Android app. I am running some Task every 2 hours.How can i check that the time has exceeded 2 hours.

I tried to use this but it says depreceated

Date date = new Date();
date.setHours(date.getHours() + 2);

I would appreciate the insight on how to implement this?

user2065795
  • 741
  • 1
  • 6
  • 8

6 Answers6

4

Check this link

http://www.dotnetexpertsforum.com/comparing-date-time-values-in-android-t1567.html

Calendar current_time = Calendar.getInstance ();
current_time.add(Calendar.YEAR, 0);
current_time.add(Calendar.DAY_OF_YEAR, 0);
current_time.set(Calendar.HOUR_OF_DAY, 
//Subtract 2 hours       
current_time.get(Calendar.HOUR_OF_DAY)-2);
current_time.set(Calendar.MINUTE, 0);
current_time.set(Calendar.SECOND, 0);

Calendar given_time = Calendar.getInstance ();
given_time.set(Calendar.YEAR, syear);
//Give the day sDay and hour shour
given_time.set(Calendar.DAY_OF_YEAR, sday);
given_time.set(Calendar.HOUR_OF_DAY, shour);
given_time.set(Calendar.MINUTE, 0 );
given_time.set(Calendar.SECOND, 0);

Date current_calendar = current_time.getTime();
Date given_calendar = given_time.getTime();

System.out.println("Current Calendar "+ current_calendar);
System.out.println("Given Calendar "+ given_calendar);

boolean v = current_calendar.after(given_calendar); 

if(v){

    return true;

}
sdg
  • 1,306
  • 1
  • 13
  • 26
3

You should use the Calendar class.

Calendar calendar=Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY)+2);
calendar.getTime();//your date +2 hours
Ovidiu Latcu
  • 71,607
  • 15
  • 76
  • 84
2

use Calendar class :

    Calendar cal = Calendar.getInstance();
    System.out.println(cal.get(Calendar.HOUR)>(cal.get(Calendar.HOUR)+2));
PermGenError
  • 45,977
  • 8
  • 87
  • 106
0

Date is deprecated. Use Calendar instead.

Source: Java: Why is the Date constructor deprecated, and what do I use instead?

Community
  • 1
  • 1
geffchang
  • 3,279
  • 2
  • 32
  • 58
0

Two hours is 2 * 60 minutes, is 2 * 60 * 60 seconds and is 2 * 60 * 60 * 1000 milliseconds. So you can just add this number of milliseconds to your date:

Date date = new Date ();
Date after2Hours = new Date (date.getTime () + 2L * 60L * 60L * 1000L);
Mikhail Vladimirov
  • 13,572
  • 1
  • 38
  • 40
0

If you have to repeat that task every two hours, you should use Alarm manager service for that. See the link below for more details.

http://www.javacodegeeks.com/2012/09/android-alarmmanager-tutorial.html

Pang
  • 9,564
  • 146
  • 81
  • 122
Varun
  • 373
  • 1
  • 2
  • 11