0

**I am trying to write the code for getting the date in required format , I have got the dates but how to add the required time with it , here I have

startDate - 1/08/2021 00:00:00 , EndDate - 20/08/2021 23:59:59 , increment days: 10

and the Expected output is :

05/08/2021 00:00:00 to 10/08/2021 23:59:59 , 11/08/2021 00:00:00 to 15/08/2021 23:59:59 ,

This is the Code which I was trying to write , any help is appreciated

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class DateTest {
    public static List<LocalDate> getDaysBetweenDates(LocalDate startDate, LocalDate endDate, int interval) {
        List<LocalDate> dates = new ArrayList<>();
        while (endDate.isAfter(startDate)) {
            dates.add(startDate);
            startDate = startDate.plusDays(interval-1);
            dates.add(startDate);
            startDate = startDate.plusDays(1);
        }
        return dates;
    }

    public static void main(String[] args) {
        int interval = 5;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss",Locale.US);
        List<LocalDate> daysBetweenDates = getDaysBetweenDates(LocalDate.parse("01-08-2021 00:00:00", formatter),
                LocalDate.parse("20-08-2021 23:59:59", formatter), interval);
        System.out.println(daysBetweenDates);
    }
}
deHaar
  • 17,687
  • 10
  • 38
  • 51

3 Answers3

3

Here's an alternative that uses LocalDates only (OK, and LocalDateTimes internally):

public static void printDaysInPeriod(LocalDate start, LocalDate end, int interval) {
    // provide some data structure that 
    Map<LocalDate, LocalDate> intervals = new TreeMap<LocalDate, LocalDate>();
    // loop through the dates in the defined period
    while (start.isBefore(end)) {
        // use the interval as step
        LocalDate intervalEnd = start.plusDays(interval);
        // store the sub-interval in the data structure
        intervals.put(start, intervalEnd);
        // and rearrange "start" to be the day after the last sub-interval
        start = intervalEnd.plusDays(1);
    }
    // provide a formatter that produces the desired output per datetime
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
                                      "dd/MM/uuuu HH:mm:ss"
                                  );
    // provide a data structure for the output parts (Strings here)
    List<String> intervalOutput = new ArrayList<>();
    // stream the sub-intervals
    intervals.entrySet().forEach(e ->
        // then produce the desired output per sub-interval and store it
        intervalOutput.add(e.getKey().atStartOfDay()
                                     .format(formatter)
                            + " to "
                            + e.getValue()
                               .atTime(LocalTime.MAX)
                               .format(formatter)));
    // finally output the sub-interval Strings comma-separated
    System.out.println(String.join(" , ", intervalOutput));
}

Using this method in a main, like this

public static void main(String[] args) {
    // example dates defining an interval
    String startInterval = "05/08/2021";
    String endInterval = "15/08/2021";
    // provide a parser that handles the format
    DateTimeFormatter dateParser = DateTimeFormatter.ofPattern("dd/MM/uuuu");
    // then parse the dates to LocalDates
    LocalDate start = LocalDate.parse(startInterval, dateParser);
    LocalDate end = LocalDate.parse(endInterval, dateParser);
    // and use the method
    printDaysInPeriod(start, end, 5);
}

produces the following output:

05/08/2021 00:00:00 to 10/08/2021 23:59:59 , 11/08/2021 00:00:00 to 16/08/2021 23:59:59
deHaar
  • 17,687
  • 10
  • 38
  • 51
1

You changed your questions a few times and in the first reading, I thought that you have start and end Date-Times as String. Based on this understanding, I wrote this answer. However, the very next minute, deHaar posted this correct answer. I am leaving this answer here for someone who will be looking for a solution to this kind of requirement (i.e. with Date-Time as String).


You can do it in the following two simple steps:

  1. Define separate DateTimeFormatter for the input and the output strings
  2. Loop through the parse range of Date-Time.

Demo

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String strStartDateTime = "1/08/2021 00:00:00";
        String strEndDateTime = "20/08/2021 23:59:59";
        DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("d/M/u H:m:s", Locale.ENGLISH);

        LocalDateTime startDateTime = LocalDateTime.parse(strStartDateTime, dtfInput);
        LocalDateTime endDateTime = LocalDateTime.parse(strEndDateTime, dtfInput);

        DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);
        for (LocalDateTime ldt = startDateTime, nextDateTime = ldt.plusDays(10).minusSeconds(1); !ldt
                .isAfter(endDateTime); ldt = ldt.plusDays(10), nextDateTime = ldt.plusDays(10).minusSeconds(1))
            System.out.println(dtfOutput.format(ldt) + " - " + nextDateTime);
    }
}

Output:

2021-08-01 00:00:00 - 2021-08-10T23:59:59
2021-08-11 00:00:00 - 2021-08-20T23:59:59

ONLINE DEMO

Learn more about the modern Date-Time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

Use the date-time API.
(The code should be self-explanatory.)

import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class DateTest {
    public static List<ZonedDateTime> getDaysBetweenDates(ZonedDateTime startDate, ZonedDateTime endDate, int interval) {
        List<ZonedDateTime> dates = new ArrayList<>();
        while (!startDate.isAfter(endDate)) {
            dates.add(startDate);
            if (Period.between(startDate.toLocalDate(), endDate.toLocalDate()).getDays() < interval) {
                startDate = endDate;
            }
            else {
                startDate = startDate.plusDays(interval);
            }
            dates.add(startDate);
            startDate = startDate.plusDays(1);
        }
        return dates;
    }

    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss", Locale.ENGLISH);
        List<ZonedDateTime> dates = getDaysBetweenDates(ZonedDateTime.of(LocalDateTime.parse("05/08/2021 00:00:00", formatter), ZoneId.systemDefault()),
                                                        ZonedDateTime.of(LocalDateTime.parse("15/08/2021 23:59:59", formatter), ZoneId.systemDefault()),
                                                        5);
        for (int i = 0; i < dates.size(); i+=2) {
            System.out.printf("%s to %s , ",
                              dates.get(i).format(formatter),
                              dates.get(i + 1).format(formatter));
        }
    }
}

Output when running above code as follows:

05/08/2021 00:00:00 to 10/08/2021 00:00:00 , 11/08/2021 00:00:00 to 15/08/2021 23:59:59 ,
Abra
  • 19,142
  • 7
  • 29
  • 41
  • format is correct just one small miss is here is that every end data timing is 23:59:59, 05/08/2021 00:00:00 to 10/08/2021 23:59:59 , 11/08/2021 00:00:00 to 15/08/2021 23:59:59 – Divyesh Kumar Jun 15 '21 at 13:15