fredrick cyril
fredrick cyril

Reputation: 81

Android Date format error

While Formatting a Date using SimpleDateFormat, I get the date and the month right. But the Year is Decreased by one. What could be the problem?

public static String getFormattedDate(String date) {

    SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-mm-dd HH:MM:SS");
    Date testDate = null;
    String newFormat="space";

    try {
        testDate = sourceFormat.parse(date);
        SimpleDateFormat formatter = new SimpleDateFormat("d/MMM/yyyy");
        newFormat = formatter.format(testDate);
        Log.i("Formatted Date",newFormat);
    }catch(Exception ex){
        ex.printStackTrace();
    }

    return newFormat;
}

The Actual date and the Formatted dates are

 01-04 15:34:00.233 21858-21858/com.cube_me.cubeme I/Actual Date: 2016-12-19 00:00:00
 01-04 15:34:00.233 21858-21858/com.cube_me.cubeme I/Formatted Date: 19/Dec/2015

Upvotes: 0

Views: 1217

Answers (2)

cyborg86pl
cyborg86pl

Reputation: 2617

It's because you have a mistake here:

yyyy-mm-dd HH:MM:SS

it should be

yyyy-MM-dd HH:mm:ss

So, you misplaced minutes (mm) with months (MM). If you pass 00 as a month, then you get December (00 is before 01 so it's parsed to 12), previous year which is correct.

Also SS are for milliseconds and ss gives you seconds.

Check the letters table here.

Upvotes: 5

seema
seema

Reputation: 991

Use

SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");

instead of

SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-mm-dd HH:MM:SS");

Upvotes: -1

Related Questions