开发者

Why is this code displaying different dates?

import java.text.ParseExcep开发者_运维知识库tion;
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?


new Date(2010, 03, 03):

This expects first parameter as year-1900, second as Month(starts with 0 as January) and the third parameter as day

The reason you are getting output as 'Sun Apr 03 00:00:00 MST 3910' => consutructor adds 1900 to the year passed as first parameter. Apr for 3rd Index.

The use of this constructor has been deprecated.

The reason for output 'Sun Jan 03 00:03:00 MST 2010': You are not using correct format, if you use "dd/MM/yyyy" then you will get the correct output.

Hope this helps


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜