Search code examples
androidandroid-calendar

Set start and end date in calendar using number of days


I am newbie in Android. I would like to use Calendar and set start and end date. Problem is, that i know only start date(today's date),but the end date is dynamically and is based on number of days. So for example: i've got int= 400 days and the end date should be something like that: start date + 400. How can i do it?

P.S Ideally would be if start and end date will be range.


Solution

  • java.time

    Consider using java.time, the modern Java date and time API, for your date work.

        ZoneId here = ZoneId.of("Europe/Tallinn");
        int numberOfDays = 400;
        
        LocalDate startDate = LocalDate.now(here);
        LocalDate endDate = startDate.plusDays(numberOfDays);
        
        System.out.format("From %s to %s%n", startDate, endDate);
    

    When I ran this snippet just now, the output was:

    From 2020-09-02 to 2021-10-07

    Advantage

    The Calendar class you asked about is poorly designed and long outdated. While it can do the job, it is cumbersome to work with, and for typical applications you will need conversions to and from Date or other classes.

    java.time is much nicer to work with.

    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 either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.

    Links