开发者

Can java.util.Calendar be passed over method?

this is my code:

import java.util.Calendar;

import java.util.Locale;

public class test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-ge开发者_如何转开发nerated method stub
        Calendar a = Calendar.getInstance();
        a.set(Calendar.MONTH, 7);
        a.set(Calendar.YEAR, 2011);
        a.set(Calendar.DAY_OF_MONTH, 16);

        System.out.print(test.getDate(a));
    }

    // What-date calculation
    public static String getDate(Calendar date) {
        //date = Calendar.getInstance();
        return date.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG,
                Locale.getDefault());
    }

}

when I run this code, it prints "Tuesday". However, I run this code on July 16, 2011 and uncomment

date = Calendar.getInstance();

so that date would be July 16, 2011 and it prints exactly "Saturday".

I wonder if the Calendar object a is passed correctly because a is also set July 16, 2011. Is there any solution for me to pass Calendar object and print the date correctly?

Thank in advance


Don't use "magic" numbers when setting Calendar's month since they are 0 based (not 1 based as you have assumed). Instead use the Calendar constants, such as Calendar.JULY.


MONTH is zero-based. So 7 is August. See the docs. There is Calendar.JULY for your convenience


That's easy - Calendar doesn't use 1-indexed months. You're setting it to August 16th. Print the toString() of the Calendar object and you'll see. Calendar provides constants that you can use as well.

You may want to check out the Joda DateTime library, which lets you use 1-indexed months more easily and solves a number of other calendaring problems.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜