代码:
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());
输出:
startTimestamp = 3912-02-01 00:00:00.0
startTimestamp.getYear() = 2012
这是一个错误还是我做错了什么?
答案 0 :(得分:1)
答案 1 :(得分:0)
请注意,new Timestamp(2012, 1, 1, 0, 0, 0, 0);
已被弃用,我认为这是您问题的根源!
改为使用Timestamp startTimestamp = new Timestamp(System.currentTimeMillis());
。
另请注意,startTimestamp.getYear()
也已弃用!
已过时。从JDK 1.1版开始,替换为 Calendar.get(Calendar.YEAR)。
返回此Date对象表示的月中的某天。该 返回的值介于1到31之间,表示该月的某天 包含或以此为代表的时刻开始 日期对象,在本地时区中解释。
考虑这个例子(基于您的原始代码):
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));
}
它会产生输出:
startTimestamp = 2012-01-01 12:00:00.0
Year = 2012