Search code examples
androiddateif-statementcalendarandroid-calendar

How to get specific date of the month programmatically?


How to get specific date of the month in android programmatically? Example, i want to get 23 april 2020 as a string or int and put it inside "if" statement.

Example

if("23 april 2020"){
// some code
} else if ("24 april 2020"){
// some code
}

Solution

  • java.time and ThreeTenABP

        LocalDate apr23 = LocalDate.of(2020, Month.APRIL, 23);
        LocalDate apr24 = LocalDate.of(2020, Month.APRIL, 24);
    
        LocalDate today = LocalDate.now(ZoneId.of("Australia/Tasmania"));
        if (today.equals(apr23)) {
            System.out.println("It’s April 23");
        } else if (today.equals(apr24)) {
            System.out.println("It’s April 24");
        } else {
            System.out.println("It’s none of those dates");
        }
    

    When I ran this snippet today (February 8 in Tasmania), the output was:

    It’s none of those dates

    Please insert your desired time zone where I put Australia/Tasmania. To use the time zone of the device use ZoneId.systemDefault(), only beware that the default may be changed by some other part of your program or any other program running in the same JVM, in which case you won’t get the device setting.

    An object of the LocalDate class from java.time represents a date. So it’s neither a string nor an int, but it’s what you need. java.time is the modern Java date and time API, it’s warmly recommended. In addition to equals() a LocalDate also has methods isAfter and isBefore. If it happens that you user doesn’t launch your app exactly on APril 23, you may use one of these for determining that the date has been passed (once the user does run the app).

    Question: Doesn’t java.time require Android API level 26?

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

    • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
    • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
    • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages. So:

      import org.threeten.bp.LocalDate;
      import org.threeten.bp.Month;
      import org.threeten.bp.ZoneId;
      

      Since you are using Gradle, this line in your build.gradle should do it (taken from Maven Repository):

         compile group: 'com.jakewharton.threetenabp', name: 'threetenabp', version: '1.2.2'
      

      If I remember correctly, this syntax works too (save any typos):

         compile 'com.jakewharton.threetenabp:threetenabp:1.2.2'
      

    Links