Nik
Nik

Reputation: 7273

Java SimpleDateFormat Seemingly Ignoring Month and Day

I have this piece of simple code:

SimpleDateFormat sqlFormatter = new SimpleDateFormat ("YYYY-MM-dd HH:mm:ss");
String temp = "2012-03-09 12:00:00";
System.out.println (temp);
Date last = sqlFormatter.parse (temp);
System.out.println (last);

I get this output:

2012-03-09 12:00:00
Sun Jan 01 12:00:00 EST 2012

I know is supposed to be simple, but I am hoping someone can quickly see what I am missing.

Upvotes: 0

Views: 603

Answers (4)

Pragalathan  M
Pragalathan M

Reputation: 1781

You need to use 'yyyy' and not 'YYYY'

Here is the output

2012-03-09 12:00:00
Fri Mar 09 12:00:00 IST 2012

for the pattern

yyyy-MM-dd HH:mm:ss

Upvotes: 1

javaCity
javaCity

Reputation: 4318

Corrected code here:

SimpleDateFormat sqlFormatter = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); String temp = "2012-03-09 12:00:00"; System.out.println(temp); Date last = sqlFormatter.parse(temp); System.out.println(last);

You should have SimpleDateFormat instead of SimpleDateFormatter and for years you give yyyy instead of YYYY.

Upvotes: 2

josh.trow
josh.trow

Reputation: 4901

Once I corrected your format String - Y is not allowed, you need y - (and the typo already mentioned) it worked fine:

SimpleDateFormat sqlFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String temp = "2012-03-09 12:00:00";
System.out.println (temp);
Date last = sqlFormatter.parse (temp);
System.out.println (last);

>2012-03-09 12:00:00
>Fri Mar 09 12:00:00 EST 2012

Upvotes: 1

Mike Bockus
Mike Bockus

Reputation: 2079

I think your pattern is a little off. I'm suprised you're not seeing an IllegalArgumentException. Try using the following pattern with lower case y's and see if that resolves your issue:

SimpleDateFormat sqlFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

Upvotes: 6

Related Questions