java.time
The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time
, the modern Date-Time API:
List<LocalDate> getDateList(int year, String monthname) {
int month = Month.valueOf(monthname.toUpperCase()).getValue();
return IntStream
.rangeClosed(1, YearMonth.of(year, month).lengthOfMonth())
.mapToObj(i -> LocalDate.of(year, month, i))
.collect(Collectors.toList());
}
Demo:
import java.time.LocalDate;
import java.time.Month;
import java.time.YearMonth;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
// Test
getDateList(2017, "February").forEach(System.out::println);
System.out.println("=*==*==*=*=");
getDateList(2016, "February").forEach(System.out::println);
}
static List<LocalDate> getDateList(int year, String monthname) {
int month = Month.valueOf(monthname.toUpperCase()).getValue();
return IntStream
.rangeClosed(1, YearMonth.of(year, month).lengthOfMonth())
.mapToObj(i -> LocalDate.of(year, month, i))
.collect(Collectors.toList());
}
}
Output:
2017-02-01
2017-02-02
...
...
...
2017-02-27
2017-02-28
=*==*==*=*=
2016-02-01
2016-02-02
...
...
...
2016-02-28
2016-02-29
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.