0

Date time set in calendar is '2016-6-18 13:54:00 ' and current date time is '2016-6-18 14:45:00' i.e. 2016-6-18 2:45 PM. In the calendar I set the MONTH value to be 5 as month is zero-based there. This is in android :

        Calendar calendar = Calendar.getInstance();

        calendar.set(Calendar.YEAR, 2016);
        calendar.set(Calendar.MONTH, 5);
        calendar.set(Calendar.DATE, 18);
        calendar.set(Calendar.HOUR_OF_DAY,13);
        calendar.set(Calendar.MINUTE,54);
        calendar.set(Calendar.SECOND,0);

        long alarmTime =calendar.getTimeInMillis();
        alarmTime = TimeUnit.MILLISECONDS.toSeconds(alarmTime);        

        long timeMillis = System.currentTimeMillis();
        long currentTimeSeconds =TimeUnit.MILLISECONDS.toSeconds(timeMillis);

        if (alarmTime > currentTimeSeconds) {

           Toast.makeText(context, "Alarm is set", Toast.LENGTH_SHORT).show();

        }else{

          Toast.makeText(context, "Alarm is not set",  Toast.LENGTH_SHORT).show();
             }

But the result shows the toast "Alarm is set" whereas I expected the otherwise i.e. "Alarm is not set".

What is going on here ?

EDIT: To my surprise, the Genymotion emulator shows 'Alarm is set' while the real device shows 'Alarm is not set'. Why is this difference ?

Istiaque Ahmed
  • 6,072
  • 24
  • 75
  • 141

2 Answers2

0

Use Calendar.getIstance().getTimeInMillis()

to compare with the first time Calendar time. Look at this answer: https://stackoverflow.com/a/16516978

in general is a good practice compare data or date generated by the same class.

Community
  • 1
  • 1
christian mini
  • 1,662
  • 20
  • 39
0

Sounds like a time zone issue.

Note that Calendar.getInstance() creates a Calendar object using the default timezone (i.e. the time zone that's configured in the device settings).

So if your Genymotion emulator is set to UTC the created Calendar object represents 2016-06-18 13:54:00 UTC which is 2016-06-18 14:54:00 GMT+1

If your device is in GTM+1, the created Calendar object represents 2016-06-18 13:54:00 GMT+1.

To fix this make sure you call Calendar.getInstance(ZimeTone) passing the correct time zone that's associated with your alarm.

Marten
  • 3,802
  • 1
  • 17
  • 26