Tyler
Tyler

Reputation: 39

How do I get my timeStamp variable to display the correct date?

So I'm having a bit of a problem getting my timeStamp to show the correct month. It keeps showing 16. What am I doing wrong? Here's the code for the variable timeStamp:

 Calendar.getInstance(TimeZone.getTimeZone("EST"));
    this.timeStamp = ((Calendar.getInstance().get(Calendar.MONTH + 1)) + "/"
            + (Calendar.getInstance().get(Calendar.DAY_OF_MONTH)) + "/"
            + (Calendar.getInstance().get(Calendar.YEAR)) + " " + (Calendar.getInstance().get(Calendar.HOUR)) + ":"
            + (Calendar.getInstance().get(Calendar.MINUTE)) + ":" + (Calendar.getInstance().get(Calendar.AM_PM)));

Upvotes: 1

Views: 39

Answers (1)

Jim Garrison
Jim Garrison

Reputation: 86774

Calendar.MONTH

is a "opaque" symbolic constant that represents the month field of a date. The term "opaque" here means that you are not meant to know or rely on the actual value, it's an encoded magic number used by the internals of the Calendar class. Adding 1 to it makes no sense (see below for details).

What you really meant was

(Calendar.getInstance().get(Calendar.MONTH) + 1) + "/" 

(notice the placement of the parentheses) to convert the month value from zero-origin to 1-origin.

As @Pillar pointed out in a comment, the code has other problems, but this is the one you asked about.


What's happening under the covers: Calendar.MONTH has the value 2, but this is not useful information. It is merely an internal index that tells the Calendar object to return the month number. In the next release (or even the next update) this value could change to something completely different.

You asked the API to return the value indexed by 3 instead. As it turns out, the value 3 corresponds to Calendar.WEEK_OF_YEAR, so your query returned the current week number. After the next JDK update it might return something different or might even throw an exception if the value 3 no longer corresponded to a valid index.

In practice the values won't change, due to backwards compatibility issues, but that doesn't mean you can rely on the symbol always having the same value.

Upvotes: 2

Related Questions