Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java SimpleDateFormat with pattern "MM/DD/yyyy" produces unexpected date value

I am trying to create a Date object from an input String. The code snippet that I have written is :

inputs are like : effDate = "03/09/2012" and ExpiryDate = "08/31/2012"

System.out.println("eff Date: " + effDate); 
SimpleDateFormat formatter = new SimpleDateFormat("MM/DD/yyyy");
Date date = formatter.parse(effDate);
System.out.println("Effective Date = " + formatter.format(date));

The output I get is :

eff Date: 03/09/2012
Effective Date = 01/09/2012

The same happens for the other input as well. like

exp date: 08/31/2012
Expiry Date = 01/31/2012

Does anyone know the reason why its changing the month value from anything(03/08) to 01 ?? Info: I am using jdk1.6 with Eclipse. And running this sample program through JUNIT 4.

like image 741
Swagatika Avatar asked Aug 30 '26 21:08

Swagatika


1 Answers

new SimpleDateFormat("MM/DD/yyyy"); should be new SimpleDateFormat("MM/dd/yyyy"); (dd instead of DD)

  • DD = Day in year
  • dd = Day in month
like image 104
KristofMols Avatar answered Sep 02 '26 12:09

KristofMols