Harshana
Harshana

Reputation: 7647

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?

Upvotes: 1

Views: 1251

Answers (3)

Stephen C
Stephen C

Reputation: 718708

For the second part of your question, you should call Calendar.get(Calendar.MILLISECONDS) to retrieve the milliseconds field of a calendar object.

Upvotes: 1

Thomas Owens
Thomas Owens

Reputation: 116161

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.

Upvotes: 1

Reese Moore
Reese Moore

Reputation: 11640

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()));

Upvotes: 2

Related Questions