1
 Calendar cal = Calendar.getInstance();
            cal.set(Calendar.YEAR,Integer.parseInt(YYYY));
            cal.set(Calendar.MONTH, Integer.parseInt(MM));
            cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(DD));
            cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hh));
            cal.set(Calendar.MINUTE, Integer.parseInt(mm));
            cal.set(Calendar.SECOND,00);
            SimpleDateFormat simpledateformat = new SimpleDateFormat("dd-MM-yyyy hh:mm");
             EditText check = (EditText) findViewById(R.id.check);
             check.setText(simpledateformat.format(cal.getTime()));

This is how I am setting time for AlarmManager to send intent on 28-11-2018 at 2:56 PM but it sends the intent as soon as I click the send Button.

Intent code

Intent sendIntent = getPackageManager().getLaunchIntentForPackage("com.whatsapp");
            try {
                PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,0,sendIntent,PendingIntent.FLAG_ONE_SHOT);
                ((AlarmManager) getSystemService(ALARM_SERVICE)).setExact(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),pendingIntent);
            }
            catch (android.content.ActivityNotFoundException ex) {
                Toast.makeText(MainActivity.this,"Please Install Whatsapp Messenger", Toast.LENGTH_LONG).show();
            }

Time Zone is UTC+5:30.

Am I setting time in the past and how to correct it?

EDIT: I used an edittext to display the time and 29-11-2018 becomes 15-06-0211.How?

EDIT:Maybe this is wrong.

 EditText date = (EditText) findViewById(R.id.date);
            String dd = date.getText().toString();

            char c[] = dd.toCharArray();
            String YYYY = c[6]+c[7]+c[8]+c[9]+"";
            String MM = c[3]+c[4]+"";
            String DD =c[0]+c[1]+"";

Answer - use substring method.But I want to know why above method is wrong?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Shivansh Khare
  • 65
  • 1
  • 10
  • What is the time in your time zone? Before or after 2:56 PM? – Ole V.V. Nov 29 '18 at 09:34
  • TIME ZONE IS UTC+5:30 – Shivansh Khare Nov 29 '18 at 10:40
  • is the instance being changed somewhere in between? check for that – touhid udoy Nov 29 '18 at 11:07
  • If what you say is correct, I believe you asked this question some time between 3 and 4 PM at UTC offset +05:30. So 2:56 PM was already in the past. – Ole V.V. Nov 29 '18 at 13:26
  • I think two answers are acceptable.I reaccepted your answer.But what to we do in such situations? – Shivansh Khare Nov 29 '18 at 14:11
  • Don’t feel ashamed to accept the answer you find *most* helpful, or toss a coin if they are equally helpful. That will be perfectly acceptable. – Ole V.V. Nov 29 '18 at 14:15
  • My reputation went down because of this :( – Shivansh Khare Nov 29 '18 at 14:46
  • 1
    FYI, the troublesome old date-time classes such as `java.util.Date`, `java.util.Calendar`, and `java.text.SimpleDateFormat` are now legacy, supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes. Most of the *java.time* functionality is back-ported to Java 6 & Java 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android in the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project. See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Nov 29 '18 at 17:05
  • Did your reputation drop because of unaccepting? Accepting an answer gives 2 reputation points, so this might explain. Also accepting an answer will help future readers see that the question has been answered at all. So if at some point you think you can accept an answer, try that. There’ll be *absolutely no* bad feelings if you don’t pick mine. You can accept and unaccept as many times as you want. [Why did I gain/lose reputation? Can I audit my reputation history?](https://meta.stackoverflow.com/questions/269653/why-did-i-gain-lose-reputation-can-i-audit-my-reputation-history) – Ole V.V. Nov 30 '18 at 12:23

2 Answers2

2

You are extracting wrong values from the EditText.
First change the format from:

"dd-MM-yyyy hh:mm"

to

"dd-MM-yyyy HH:mm"

because your format uses 12 hour clock and not 24 hour.
and then use these values:

String DD = dd.substring(0, 2);
String MM = dd.substring(3, 5);
String YYYY = dd.substring(6, 10);
String hh = dd.substring(11, 13);
String mm = dd.substring(14, 16);
forpas
  • 160,666
  • 10
  • 38
  • 76
2

java.time

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
    DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:mm a");
    ZoneId zone = ZoneId.of("Asia/Kolkata");

    String dateString = "29-11-2018";
    String timeString = "2:56 PM";
    LocalDate alarmDate = LocalDate.parse(dateString, dateFormatter);
    LocalTime alarmTime = LocalTime.parse(timeString, timeFormatter);
    long triggerAlarmAtMillis = alarmDate.atTime(alarmTime)
            .atZone(zone)
            .toInstant()
            .toEpochMilli();

    System.out.println("Alarm will happen at millis " + triggerAlarmAtMillis);

Output is:

Alarm will happen at millis 1543483560000

You may use an online epoch time converter to verify that this corresponds to GMT: Thursday 29. November 2018 09:26:00, which in turn is the same as 14:56 at offset +05:30. Link at the bottom.

Consider avoiding Calendar and SimpleDateFormat

The date-time classes you were using have heavy design problems and are considered long outmoded. I recommend you use java.time instead. If necessary for your Android API level, then through ThreeTenABP, see below.

Also I recommend you leave date and time parsing to the library methods. Neither pick out single characters nor substrings for this purpose, it is the hard and error-prone way.

But I want to know why above method is wrong?

It’s an ugly and surprising fact of Java that in many places int and char can be used interchangeably (this has been taken over from C++ and its forerunners). For example:

    String MM = c[3]+c[4]+"";

c[3] and c[4] are both 1, and you had expected this to give the string "11". It doesn’t. The expression is evaluated from left to right, so the int equivalents of the chars are added. 1 is represented as the number 49. 49 + 49 equals 98. When you add 98 to the empty string, it is first converted to a string itself (as expected), so you get the string "98". Similarly for date you get 50 + 57 = 107, and for year 50 + 48 + 49 + 56 = 203.

Next surprise (I suppose). While setting the year of a Calendar to 203 may make sense, setting the month to 98 ought to be an error and result in an exception, right? Not with the Calendar class with default settings. It just keeps counting months into the years after year 203 and ends up in year 211. Similar when you set the day of month to 107, it keeps counting days into the following months and ends at Sat Jun 15 211 — still more than 1800 years ago.

And yet there is one more bug in your code. Here:

    cal.set(Calendar.MONTH, Integer.parseInt(MM));

Even if MM had been 11 as intended, this would not set the month to November. Another confusing thing about Calendar is that month numbers are 0-based: 0 is January and so on, so 11 is December, not November.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on new Android devices (from API level 26, I’m told) the new API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310, where the modern API was first described).
  • On (older) Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. Make sure you import the date and time classes from package org.threeten.bp and subpackages.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161