Search code examples
javaandroidalarmmanager

Android set specific time and date in Alarm Manager


I want to set time and date in AlarmManager. When I run the app it prints a different date but time is correct. Why does it show a different date on log cat?

Here is my example code:

String strMinusDate ="22-08-2014";

String[] splitDate_Parts = strMinusDate.split("-");
saparated_Day = splitDate_Parts[0];
saparated_Month = splitDate_Parts[1];
saparated_Year = splitDate_Parts[2];

int convertDay = Integer.valueOf(saparated_Day);
int convertMonth = Integer.valueOf(saparated_Month);
int convertYear =  Integer.valueOf(saparated_Year); 

cal.set(convertYear, convertMonth, convertDay, 3 , 16);
Date dt=cal.getTime();
System.out.println("dt " + dt);

Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(Xyz.this, 1, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);

Here is Logcat info

08-22 15:04:35.252: I/System.out(811): dt Mon Sep 22 03:16:59 GMT+05:30 2014

Solution

  • Months in Java are zero-based, which means January is 0. This makes September 22nd the technically correct outcome, but not the one you'd expect. A simpler solution would be the following:

    SimpleDateFormat df = new SimpleDataFormat("dd-MM-yyyy");
    Date dt = df.parse("22-08-2014");
    System.out.println("dt " + dt);