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*.
Solution using java.time
, the modern Date-Time API:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
int dpYear = 2010, dpMonth = 1, dpDayOfMonth = 15;
// In DatePicker, the month is indexed starting at 0. Check
// https://stackoverflow.com/a/4467894/10819573 to learn more.
dpMonth++;
LocalDate date = LocalDate.of(dpYear, dpMonth, dpDayOfMonth);
System.out.println(date);
// Formatted output
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMMM dd uuuu", Locale.ENGLISH);
String formatted = dtf.format(date);
System.out.println(formatted);
}
}
Output:
2010-02-15
Mon February 15 2010
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.