Matej Košút Matej Košút - 26 days ago 22
Android Question

Android: SimpleDateFormat changes year of my date

I am using SimpleDateFormat to change format of date, shown below. But it somehow changes my year from for example 2016 to 2019 or 2018. How could I make it work correctly?

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);

Answer

You must be careful to use the right casing (either upper or lower) for all the date/time pattern strings, as specified in the SimpleDateFormat Javadoc.

Uppercase M is used for "Month in year", and lowercase m is used for "Minute in hour".

Uppercase S is used for "Millisecond", and lowercase s is used for "second in minute".

This should work properly:

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);
Comments