java date.getyear,为什么Java的Date.getYear()返回111而不是2011?

在尝试将字符串解析为Date对象时遇到了问题。使用SimpleDateFormat解析后,通过.getYear()获取年份返回的是错误值。解决方案是使用Calendar类代替,通过Calendar.get()方法正确获取年、月和日。
摘要由CSDN通过智能技术生成

I am having a bit of trouble parsing a string date to a Date object. I use a DateFormat to parse the string, and when I print the value of the date, it gives me what I expect.

But when I try get the day, the month or the year it gives me the wrong values. For instance, the year is 2011, but when I do .getYear() it gives me 111. I have no idea why this is happening. Here is the relevant code segment:

Date dateFrom = null;

String gDFString = g.getDateFrom();

System.out.println(gDFString);

DateFormat df = new SimpleDateFormat("dd/MM/yyyy");

try {

dateFrom = df.parse("04/12/2011");

System.out.println(dateFrom);

System.out.println(dateFrom.getYear());

} catch (ParseException e) {

e.printStackTrace();

}

When I out print dateFrom, I get Sun Dec 04 00:00:00 GMT 2011, which is what you would expect. But printing .getYear() returns 111.

I need to be able to get the day, month and year of the date for a time series graph.

解决方案

Those methods have been deprecated. Instead, use the Calendar class.

import java.text.DateFormat;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Calendar;

public final class DateParseDemo {

public static void main(String[] args){

final DateFormat df = new SimpleDateFormat("MM/dd/yyyy");

final Calendar c = Calendar.getInstance();

try {

c.setTime(df.parse("04/12/2011"));

System.out.println("Year = " + c.get(Calendar.YEAR));

System.out.println("Month = " + (c.get(Calendar.MONTH)));

System.out.println("Day = " + c.get(Calendar.DAY_OF_MONTH));

}

catch (ParseException e) {

e.printStackTrace();

}

}

}

Output:

Year = 2011

Month = 3

Day = 12

And as for the month field, this is 0-based. This means that January = 0 and December = 11. As stated by the javadoc,

Field number for get and set indicating the month. This is a

calendar-specific value. The first month of the year in the Gregorian

and Julian calendars is JANUARY which is 0; the last depends on the

number of months in a year.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值