0

I was bitten by the problem described here: Android DatePicker year problem . In a nutshell, Android's DatePicker expects years to be specified in years (2011 is 2011), while Java's Date class starts at 1900 (so 2011 is actually 111).

Is there a better way to intermix Date and DatePickers, other than adding and substracting 1900 when doing the conversions?

Itay.

Community
  • 1
  • 1
zmbq
  • 38,013
  • 14
  • 101
  • 171
  • This is one of many reasons to never use the terrible legacy classes `Date`, `Calendar`, `SimpleDateFormat`, and such. Use only *java.time* classes. See the modern solution in [Answer by Avinash](https://stackoverflow.com/a/68398163/642706). – Basil Bourque Jul 15 '21 at 20:56

2 Answers2

2

Yes - don't use the deprecated methods in Date to work with day/month/year values. Date just represents an instant in time - you should use Calendar if you want to translate that into some appropriate human breakdown into days, months, years etc - and to apply time zones.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

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.

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