First of all, read the javadoc. The lowercase mm
pattern corresponds to the minutes. To get the months, you need to use uppercase MM
. So, your formatter will be like this:
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
And you don't need to do this:
DateTime dateTime1 = new DateTime(dt1);
It's redundant, because you're creating 2 identical objects. Just use the dates returned by parseDateTime
method. Or just do:
DateTime dateTime1 = dt1;
And you've already created a DateTimeFormatter
, so just use it to format the output as well. Instead of:
System.out.println(dateTime1);
Do this:
System.out.println(formatter.print(dateTime1));
The print
method will return the dates in the format you want.
I'm not sure if you wanted to print the first date (2017-06-21 00:00:00
). If you want this, just change the order of the plusMinutes
and System.out.println
lines.
New Java Date/Time API
Joda-Time is in maintainance mode and is being replaced by the new APIs, so I don't recommend start a new project with it. Even in joda's website it says: "Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to java.time (JSR-310).".
So, if you can migrate your Joda-Time code, or starting a new project, consider using the new API. If you're using Java 8, you can use the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time
and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp
), but the classes and methods names are the same.
The logic is very similar. The only difference is that I used LocalDateTime
class, and to convert it to a java.util.Date
I need to know in what timezone it is. I used the system's default timezone, which is probably what you want (as your original code also uses the default timezone):
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime1 = LocalDateTime.parse("2017-06-21 00:00:00", formatter);
LocalDateTime dateTime2 = LocalDateTime.parse("2017-06-23 00:00:00", formatter);
List<Date> allDates = new ArrayList();
while (dateTime1.isBefore(dateTime2)) {
// get the date in the system default timezone and convert to java.util.Date
allDates.add(Date.from(dateTime1.atZone(ZoneId.systemDefault()).toInstant()));
dateTime1 = dateTime1.plusMinutes(15);
System.out.println(formatter.format(dateTime1));
}
In Java 8 the Date.from
method is available. In ThreeTen Backport (Java 7 and Android), you can use the org.threeten.bp.DateTimeUtils
class instead:
allDates.add(DateTimeUtils.toDate(dateTime1.atZone(ZoneId.systemDefault()).toInstant()));