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

发布于 2024-12-01 14:42:00 字数 789 浏览 1 评论 0原文

我在将字符串日期解析为 Date 对象时遇到了一些麻烦。我使用 DateFormat 来解析字符串,当我打印日期值时,它给出了我所期望的结果。

但是当我尝试获取日期、月份或年份时,它给了我错误的值。例如,年份是 2011 年,但是当我执行 .getYear() 时,它给了我 111。我不知道为什么会发生这种情况。以下是相关的代码段:

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

当我输出 dateFrom 时,我得到 Sun Dec 04 00:00:00 GMT 2011,这正是您所期望的。但打印 .getYear() 返回 111

我需要能够获取时间序列图的日期、月份和年份。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

江湖正好 2024-12-08 14:42:00

这些方法已被弃用。相反,请使用 Calendar 类。


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

输出

Year = 2011
Month = 3
Day = 12

对于月份字段,这是从0开始的。这意味着 1 月 = 0 且 12 月 = 11。正如 javadoc 中所述,

表示月份的 get 和 set 字段编号。这是一个
特定于日历的值。公历一年中的第一个月
儒略历是JANUARY,即0;最后取决于
一年中有多少个月。

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.

地狱即天堂 2024-12-08 14:42:00

Javadoc 来救援:

已弃用。从 JDK 版本 1.1 开始,替换为
Calendar.get(Calendar.YEAR) - 1900。

返回一个值,该值是从 1900 中减去 1900 的结果。
包含或开始于以下时间点的年份
此日期对象,按照本地时区解释。

您不应该使用已弃用的方法。已弃用的方法是不应再使用的方法。但无论您使用哪种方法,请阅读其 javadoc 以了解它的作用。

Javadoc to the rescue:

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

Returns a value that is the result of subtracting 1900 from the
year that contains or begins with the instant in time represented by
this Date object, as interpreted in the local time zone.

You should not use deprecated methods. Deprecated methods are methods which should not be used anymore. But whatever the method you're using, read its javadoc to know what it does.

不…忘初心 2024-12-08 14:42:00

邪恶总统成功了,Date.getYear() 返回一个值,该值是从包含的年份中减去 1900 的结果。而你不应该使用它。

但问题中代码的快速修复是:

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

    // Add 1900 to dateFrom.getYear() 

    System.out.println(dateFrom.getYear()+1900);
} catch (ParseException e) {
    e.printStackTrace();
}

President Evil nailed it, Date.getYear() returns a value that is the result of subtracting 1900 from the year that contains. And you you shouldn't use it.

But quick fix for the code in the question is:

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

    // Add 1900 to dateFrom.getYear() 

    System.out.println(dateFrom.getYear()+1900);
} catch (ParseException e) {
    e.printStackTrace();
}
裂开嘴轻声笑有多痛 2024-12-08 14:42:00

http://download .oracle.com/javase/1.4.2/docs/api/java/util/Date.html#getYear%28%29

规范指出它返回减去 1900 的年份。可能是避免的好主意也已弃用的方法。

http://download.oracle.com/javase/1.4.2/docs/api/java/util/Date.html#getYear%28%29

The specification states that it returns the year minus 1900. Probably a good idea to avoid deprecated methods as well.

溇涏 2024-12-08 14:42:00

太长了;博士

int year = 
    LocalDate.parse( 
        "04/12/2011" , 
        DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( Locale.US ) 
    ).getYear() ;  

2011

java.time

麻烦的 java.util.Date 类及其同级现在被优秀的 java.time 类所取代。

String input = "04/12/2011";
Locale locale = Locale.US;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( locale );
LocalDate ld = LocalDate.parse( input , f );

java.time 类使用合理的编号,其中:

  • 2011 年1 月至 12 月的月份 1-12
  • 表示 2011
  • 年星期一至星期日的星期数为 1-7(根据 ISO 8601)。

询问 LocalDate 的组成部分。

int year = ld.getYear();  // 2011
int month = ld.getMonthValue();  // 4
int dayOfMonth = ld.getDayOfMonth();  // 12

您甚至可以要求自动本地化的月份名称和星期名称。

String monthName = ld.getMonth().getDisplayName( TextStyle.FULL_STANDALONE , Locale.CANDA_FRENCH ); // avril

关于 java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧日期时间类,例如 java.util.Date、.Calendar 和 & 。 java.text.SimpleDateFormat

Joda-Time 项目,现已在 维护模式,建议迁移到 java.time。

要了解更多信息,请参阅 Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。

许多 java.time 功能都向后移植到 Java 6 和 Java 6。 ThreeTen-Backport 中的 7 并进一步适应 AndroidThreeTenABP(请参阅如何使用...) 。

ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是 java.time 未来可能添加的内容的试验场。您可能会在这里找到一些有用的类,例如 IntervalYearWeekYearQuarter 等。

tl;dr

int year = 
    LocalDate.parse( 
        "04/12/2011" , 
        DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( Locale.US ) 
    ).getYear() ;  

2011

java.time

The troublesome java.util.Date class and its siblings are now supplanted by the excellent java.time classes.

String input = "04/12/2011";
Locale locale = Locale.US;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( locale );
LocalDate ld = LocalDate.parse( input , f );

The java.time classes utilize sane numbering, with:

  • Months 1-12 for January-December
  • 2011 means 2011
  • Days of week are 1-7 for Monday-Sunday (per ISO 8601).

Interrogate the LocalDate for its constituent parts.

int year = ld.getYear();  // 2011
int month = ld.getMonthValue();  // 4
int dayOfMonth = ld.getDayOfMonth();  // 12

You can even ask for automatically localized name of month and name of day-of-week.

String monthName = ld.getMonth().getDisplayName( TextStyle.FULL_STANDALONE , Locale.CANDA_FRENCH ); // avril

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

雪化雨蝶 2024-12-08 14:42:00

这只是一个猜测,但 111 可能是自 1900 年以来的年数。查看文档/做一些测试来验证这一点(我目前无法检查)

This is only a guess, but the 111 could be the number of years since 1900. Take a look at documentation/do some tests to verify this (I can't check at the moment)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文