tags:

views:

94

answers:

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

public class DateDemo {

    public static void main(String[] args) throws ParseException {

        SimpleDateFormat datef = new SimpleDateFormat("dd/mm/yyyy");

        Date date1 = new Date(2010, 03, 03) ;
        Date date2 = datef.parse("03/03/2010") ;

        System.out.println( date1 );
        System.out.println( date2 );
    }
}

is giving following output:

Sun Apr 03 00:00:00 MST 3910

Sun Jan 03 00:03:00 MST 2010

Why it is giving different results?

+1  A: 

From java sources:

@Deprecated
public Date(int year, int month, int date, int hrs, int min, int sec) {
    int y = year + 1900;
    // month is 0-based. So we have to normalize month to support Long.MAX_VALUE.
    if (month >= 12) {
        y += month / 12;
        month %= 12;
    } else if (month < 0) {
        y += CalendarUtils.floorDivide(month, 12);
        month = CalendarUtils.mod(month, 12);
    }
    BaseCalendar cal = getCalendarSystem(y);
    cdate = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.getDefaultRef());
    cdate.setNormalizedDate(y, month + 1, date).setTimeOfDay(hrs, min, sec, 0);
    getTimeImpl();
    cdate = null;
}

As you can see, year is a bit tricky parameter.


btw, you operate with octal numbers but there is no need to do that and it leads to error with higher numbers.

Roman
Good one Roman. Yeah, never write integer literals with a leading 0 in Java! It isn't the bug here as you say but another one waiting to happen.
Sean Owen
Wouldn't the API documentation (a.k.a the JavaDoc) be a better source of information here? http://java.sun.com/javase/6/docs/api/java/sql/Date.html#Date(int,%20int,%20int)
Joachim Sauer
@Joachim: It's a matter of taste imho)
Roman
@Roman: partially. But one of those is the authoritative reference and the other is just one of any number of possible implementations.
Joachim Sauer
+1  A: 

You have two bugs.

  1. The last post answered this but maybe didn't crystallize the punchline: To specify the year 2010, pass "110" as the parameter. Year is specified in years since 1900.

  2. Your format pattern is using "mm" for months. That's the pattern for minutes. Use "MM" instead.

Sean Owen
Also: the month is zero-based in that constructor. So the OP has 3 errors in total.
Joachim Sauer
@Sean Owen : even this is not working :- SimpleDateFormat datef = new SimpleDateFormat("dd-MM-yyyy");Date date1 = new Date(110, 3, 3) ;Date date2 = datef.parse("3-3-2010") ;
rits
@rits: re-read the JavaDoc to the Date constructor you use (posted in my other comment below) and check the month field. Also read my comment just above.
Joachim Sauer
+2  A: 
hp
Sometimes I wonder why documentation is written at all...
extraneon