3

I was checking the code I wrote a few years ago. Then I realised that Android Studio is giving an annotation at Calendar.AM, it says it must be one of Calendar.SUNDAY, Calendar.MONDAY and so on...

Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, minute);

c.add(Calendar.MINUTE, -90 * (pos + 1) - 14);
hour = c.get(Calendar.HOUR);
minute = c.get(Calendar.MINUTE);
boolean am = (c.get(Calendar.AM_PM) == Calendar.AM);
if (hour == 0) hour = 12;
String time = hour + ":";
time += (minute < 10) ? "0" + minute : minute;
time += (am) ? " AM" : " PM";
return time;

I just want to make a boolean check whether it's AM or PM and set the time accordingly. The program is working though.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Ege Kuzubasioglu
  • 5,991
  • 12
  • 49
  • 85
  • Class Calendar is designed in "old school", with integer constants, not enum. So use proper constant rely ONLY on programmers, is not "type safe". – Jacek Cz Sep 09 '17 at 13:13
  • I don't understand You, class Javadoc say differently – Jacek Cz Sep 09 '17 at 13:14
  • The message doesn’t seem to make sense. [The documentation of `Calender.AM`](http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#AM) says “Value of the `AM_PM` field indicating the period of the day from midnight to just before noon.”. There would be no reason at all in comparing to, say, `Calendar.SUNDAY` instead. – Ole V.V. Sep 09 '17 at 13:35
  • 1
    If you were going to write that code today, two suggestions: (1) use a formatter for formatting the time rather reinventing the wheel (2) consider getting the modern Java date & time API in [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) so you can use `LocalTime` and `DateTimeFormatter`. The modern classes are generally much nicer to work with. – Ole V.V. Sep 09 '17 at 13:43
  • Like this: `String time = LocalTime.of(hour, minute).minusMinutes(90 * (pos + 1) + 14).format(DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH));` – Ole V.V. Sep 09 '17 at 13:50
  • 1
    Why the downvote, please? The code may not be strictly minimal, but it’s nice and short, and the question may not be put in her Majesty’s best English, but I think we can understand it. Most of all I think it’s a perfectly valid and interesting question. – Ole V.V. Sep 09 '17 at 15:15
  • Maybe a bug in Android Studio which emits a wrong warning (annotation). – Meno Hochschild Sep 10 '17 at 23:08

1 Answers1

2

Had the same problem with some legacy code I am currently working on.

I found this issue being tracked here: https://issuetracker.google.com/issues/37122723

However, it seems like they won't be fixing it as it comes from IntelliJ: https://youtrack.jetbrains.com/issue/IDEA-144891

It shouldn't affect your code though, as it is only a code analysis/inspection bug.