简体   繁体   中英

Java Calendar date manipulation issue

I am try to get the current date/time in in following format,

SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z"); 
// should display something similar to  2001.07.04 AD at 12:08:56 PDT
Calendar calendar = Calendar.getInstance();
calendar.set(2009, 2, 4, 10, 22, 44);
format.format( calendar.getTime() );
System.out.println(calendar.getTime());

But it display as Wed Mar 04 10:22:44 IST 2009.

The second question is I want to see the milliseconds value of the set time.

System.out.println(calendar.getTimeInMillis());

But it always return the current times milliseconds value and not the time I set earlier.

What is I am missing here?

The SimpleDateFormat#format(Object) method returns a formatted String , it does not affect how the Calendar#getTime() method returns. To that end you should do a:

System.out.println(format.format(calendar.getTime()));

The first problem that I see is that format.format(calendar.getTime()); returns a String and doesn't actually change the formatting of the Calendar. You are going to want to replace the last two lines with System.out.println(format.format(calendar.getTime())); to actually print out the date using the format you specify (assuming your SimpleDateFormat is valid, but it looks OK at a quick glance).

Not sure about the second problem you are having, unfortunately, but I have a place for you to start. I'm not a fan of the wording of the Javadocs for getTime() and getTimeInMillis() . The getTime() method returns "a Date object representing this Calendar 's time value" while getTimeInMillis() returns "the current time as UTC milliseconds from the epoch". To me, the difference in wording implies that getTimeInMillis() doesn't use the date specified by the Calendar object, even though it is an instance method. Try System.out.println(calendar.getTime().getTime()); in order to call the getTime() method on the Date representation of the Calendar, which is document to return the time in milliseconds between 1 January 1970 and the date represented by the Date object.

对于问题的第二部分,您应该调用Calendar.get(Calendar.MILLISECONDS)来检索日历对象的毫秒字段。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM