Android: SimpleDateFormat 改变了我约会的年份

Android: SimpleDateFormat changes year of my date

我正在使用 SimpleDateFormat 更改日期格式,如下所示。但它以某种方式将我的年份从 2016 年更改为 2019 年或 2018 年。我怎样才能让它正常工作?

    String date = "2016-10-22 13:45:46.000000";

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:MM:SS");
    Date testDate = null;
    try {
        testDate = sdf.parse(date);
    }catch(Exception ex){
        ex.printStackTrace();
    }
    SimpleDateFormat formatter = new SimpleDateFormat("dd.mm.yyyy HH:MM");
    String newFormat = formatter.format(testDate);

您必须小心对所有 date/time 模式字符串使用正确的大小写(大写或小写),如 SimpleDateFormat Javadoc.

中所指定

大写M用于"Month in year",小写m用于"Minute in hour"。

大写S用于"Millisecond",小写s用于"second in minute"。

这应该可以正常工作:

String date = "2016-10-22 13:45:46.000000";

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date testDate = null;
try {
    testDate = sdf.parse(date);
}catch(Exception ex){
    ex.printStackTrace();
}

SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");
String newFormat = formatter.format(testDate);