This is a possible duplicate, but I'm not able to figure out why the month is returned as zero when specified as MMM and works well with mm(numeric). Any help here would be really appreciated?
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.Locale;
public class time1 {
public static void main(String[] args) {
DateFormat originalFormat = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
DateFormat targetFormat = new SimpleDateFormat("yyyy-mm-dd");
Date date = null;
try {
date = originalFormat.parse("26-Aug-2011");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String formattedDate = targetFormat.format(date);
System.out.println("old date: " + date);
System.out.println("new date: " + formattedDate);
}
}
The output is:
old date: Fri Aug 26 00:00:00 IST 2011
new date: 2011-00-26
When the format is changed to dd-mm-yyyy and the date is 26-08-2011, the output is
old date: Wed Jan 26 00:07:00 IST 2011
new date: 2011-07-26
I'm not able to understand the reason it fails with MMM, all my dates are in the format(26-Aug-2011) and I need to convert them to yyyy-mm-dd (26-07-2011).
From the documentation, I can say that
DateFormat targetFormat = new SimpleDateFormat("yyyy-mm-dd");
needs to be changed to
DateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
// this gives you the Date in Digits.
As per documentation,
'M' is used for Month in Year, whereas
'm' is used for Minute in Hour.
Hence, your 'mm' is returning the Minutes which it takes as 00:00 by default which is the output you have been getting. This will give you the following Output.
old date: Fri Aug 26 00:00:00 IST 2011
new date: 2011-08-26
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With