0

Code:

import java.sql.Timestamp;
Timestamp startTimestamp = new Timestamp(2012, 1, 1, 0, 0, 0, 0);
System.out.println("startTimestamp = " + startTimestamp);
System.out.println("startTimestamp.getYear() = " + startTimestamp.getYear());

Output:

startTimestamp = 3912-02-01 00:00:00.0
startTimestamp.getYear() = 2012

Is it a bug or am I doing something wrong?

2 Answers 2

1

The javadoc says:

Parameters: year - the year minus 1900

So, 2012+1900=3912.

Sign up to request clarification or add additional context in comments.

1 Comment

My date is 2012 and should we ok with the long timestamp, right?
0

Note, that new Timestamp(2012, 1, 1, 0, 0, 0, 0); is deprecated and I think is the root of your problem!

Use Timestamp startTimestamp = new Timestamp(System.currentTimeMillis()); instead.

Also, note that startTimestamp.getYear() is also deprecated!

Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.YEAR).

Returns the day of the month represented by this Date object. The value returned is between 1 and 31 representing the day of the month that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.

Consider this example (based on your original code):

public static void main(String[] args)
{
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.DAY_OF_YEAR, 1);
    cal.set(Calendar.MONTH, 1);
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    Timestamp startTimestamp = new Timestamp(cal.getTimeInMillis());
    System.out.println("startTimestamp = " + startTimestamp);
    Calendar cal2 = Calendar.getInstance();
    cal2.setTimeInMillis(startTimestamp.getTime());
    System.out.println("Year = " + cal2.get(Calendar.YEAR));
}

It would produce output:

startTimestamp = 2012-01-01 12:00:00.0
Year = 2012

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.