-1

I am trying to make an application which takes start date, start time and end time. If the end time does not lie in the start date then how I can calculate the ending date based on the end time.

Here is the screenshot of what I want

image

As you can see in the picture when you enter start date, start time and end time, the end time is ending on the next date, it is automatically calculating the end date. (I also underlined it.)

How I can achieve this things? What the logic behind.

luk2302
  • 55,258
  • 23
  • 97
  • 137
  • 1
    Add a certain amount of a temporal unit to the start date, maybe? What API do you use for time? I know Android only supports `java.time` (which should be used preferably) in newer versions, I think from API level 24 or higher... – deHaar Sep 18 '19 at 08:40
  • 1
    Yes I am using that. – Muhammad Hashim Shafiq Sep 18 '19 at 08:49

1 Answers1

2

java.time

    ZoneId zone = ZoneId.of("America/Chicago");
    DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:mm a (OOOO)", Locale.US);

    LocalDate startDate = LocalDate.of(2019, Month.SEPTEMBER, 18);
    LocalTime startTime = LocalTime.of(14, 0);
    LocalTime endTime = LocalTime.of(4, 0);

    ZonedDateTime start = ZonedDateTime.of(startDate, startTime, zone);
    ZonedDateTime end = ZonedDateTime.of(startDate, endTime, zone);
    if (end.isBefore(start)) {
        end = ZonedDateTime.of(startDate.plusDays(1), endTime, zone);
    }

    System.out.println("Date: " + startDate);
    System.out.println("Start Time: " + start.format(timeFormatter));
    System.out.println("End Time: " + end.format(timeFormatter));
    System.out.println("Ends on " + end.toLocalDate());

Output from this snippet is:

Date: 2019-09-18
Start Time: 2:00 PM (GMT-05:00)
End Time: 4:00 AM (GMT-05:00)
Ends on 2019-09-19

I have shown you how to use a DateTimeFormatter for formatting the times. You will probably want to use formatters for the dates too.

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 newer Android devices (from API level 26) the modern API comes built-in.
  • In 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.

Links

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