Android 日期类中的年份不正确
我正在尝试比较日期,并且发现我的代码出了问题,但我不知道为什么。
我正在尝试将日期与今天的日期进行比较(仅使用公历)。我已经在代码中提到的地方打印出了今天的日期,并且在一个地方它神奇地从 2010 年更改为 3910 年(今天的年份 + 1900)。
有谁知道这有什么原因吗?
//Prints out 2010
System.out.println("TodaysDate.getYear():\t"+todaysDate.getYear());
//Prints out 2010
System.out.println(todaysDate);
//Getting a year from a string (it is 2010)
todaysDate.setYear(Integer.parseInt(yea));
//Prints out 2010
System.out.println("TodaysDate.getYear():\t"+todaysDate.getYear());
//Prints out 3910
System.out.println(todaysDate);
I am trying to compare dates and I have found where my code goes wrong, but I don't know why.
I am trying to compare a date with today's date (using Gregorian calendars only). I have printed out today's date where ever it is mentioned in the code and in one place it magically changes from year 2010 to year 3910 (today's year + 1900).
Does anyone know any reason for this?
//Prints out 2010
System.out.println("TodaysDate.getYear():\t"+todaysDate.getYear());
//Prints out 2010
System.out.println(todaysDate);
//Getting a year from a string (it is 2010)
todaysDate.setYear(Integer.parseInt(yea));
//Prints out 2010
System.out.println("TodaysDate.getYear():\t"+todaysDate.getYear());
//Prints out 3910
System.out.println(todaysDate);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该日期通常存储为“自 1900 年以来的年数”,因此您需要对此进行补偿。您可以在
Date
的文档中看到: http: //developer.android.com/reference/java/util/Date.html编辑:我应该提到我作为评论发布的内容。 Jeff Sharkey 建议不要使用 Calendar 类(如果您也使用它)。 android.text.format.DateUtils 更加轻量级(当您第一次加载 Calendar 类时,您会发现手机会稍微停顿,尤其是在旧手机上)。 DateUtils 适用于 Android 1.5 及更高版本。
The date is typically stored as "number of years since 1900", so you need to compensate for that. You can see that in the documentation for
Date
: http://developer.android.com/reference/java/util/Date.htmlEDIT: I should mention what I posted as a comment. Jeff Sharkey recommended against the Calendar class (if you're using that too). android.text.format.DateUtils is much more lightweight (you'll see that the phone stalls for a little bit when you first load the Calendar class, especially on old phones). DateUtils is available in Android 1.5 and up.