1

I am trying to parse a date format string and then print out the formatted string for the same pattern. I am expecting them to be the same. But the output is not agreeing with the input. Any help is much appreciated

Here is my code

import java.text.SimpleDateFormat;
import java.util.Date;

public class Test{
    public static void main(String[] args) {
    String pattern=args[0];
    String dtstr = args[1];
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
    Date date = new Date();
    try {
        //
        String fmtd = sdf.format(date);
        System.out.println("The formatted string: " +fmtd);
        System.out.println("The parsed date is: " + sdf.format(sdf.parse(fmtd)));
        System.out.println("The parsed date from input is: " + sdf.format(sdf.parse(dtstr)));
    } catch (Exception e) {
        e.printStackTrace();
    }
  }
}

Here is how I invoke this

JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64/ sudo java Test "EEE MMM dd YYYY HH:mm:ss Z (zzzz)" "Sun Sep 22 2013 20:03:46 +0530 (India Standard Time)"

Here is the output

The formatted string: Wed Sep 25 2013 19:55:57 +0000 (Coordinated Universal Time)
The parsed date is: Wed Jan 02 2013 19:55:57 +0000 (Coordinated Universal Time)
The parsed date from input is: Sun Dec 30 2013 20:03:46 +0530 (India Standard Time)

I am expecting the formatted string and the parsed strings to be identical What I am doing wrong?

Ram
  • 1,297
  • 1
  • 11
  • 17

1 Answers1

4

You are using YYYY in your format string. It should be yyyy:

"EEE MMM dd yyyy HH:mm:ss Z (zzzz)";

Y is for Week Year:

A week year is in sync with a WEEK_OF_YEAR cycle. All weeks between the first and last weeks (inclusive) have the same week year value. Therefore, the first and last days of a week year may have different calendar year values.

For example, January 1, 1998 is a Thursday. If getFirstDayOfWeek() is MONDAY and getMinimalDaysInFirstWeek() is 4 (ISO 8601 standard compatible setting), then week 1 of 1998 starts on December 29, 1997, and ends on January 4, 1998. The week year is 1998 for the last three days of calendar year 1997. If, however, getFirstDayOfWeek() is SUNDAY, then week 1 of 1998 starts on January 4, 1998, and ends on January 10, 1998; the first three days of 1998 then are part of week 53 of 1997 and their week year is 1997.

With the changed pattern, you will get following output:

The formatted string: Thu Sep 26 2013 01:32:09 +0530 (India Standard Time)
The parsed date is: Thu Sep 26 2013 01:32:09 +0530 (India Standard Time)
The parsed date from input is: Sun Sep 22 2013 20:03:46 +0530 (India Standard Time)
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525