获取当前年份和月份产生奇怪的结果 [英] Getting current Year and Month resulting strange results

查看:136
本文介绍了获取当前年份和月份产生奇怪的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作涉及到Android学习项目。我想获得本年度&安培;使用下面code,但它不是为我工作一个月。

I am working on a learning project related to Android. I am trying to get current year & month by using below code but it not works for me.

GregorianCalendar gc = new GregorianCalendar();
gc.YEAR // returning 1       
gc.MONTH // returning 2

Calendar c = Calendar.getInstance();
c.YEAR // returning 1       
c.MONTH // returning 2

有人能帮助我吗?难道我做错了什么?请原谅我,我是新来的Java开发。谢谢。

Can someone help me? Am i doing something wrong? please forgive me i am new to java development. thanks.

推荐答案

为了给多一点背景:

两者新的GregorianCalendar() Calendar.getInstance()将给予正确的当前日期初始化的日历和时间。

Both new GregorianCalendar() and Calendar.getInstance() will correctly give a calendar initialized at the current date and time.

常量的的的 日历 类。你应该的的使用它们内经的参考,这使它看起来像他们一个对象的状态的一部分。这是日历类,访问不同的字段的值设计的一个不幸的一部分,你需要调用 GET 使用一个场号,如图其他答案指定为这些常数之一,

MONTH and YEAR are constants within the Calendar class. You should not use them "via" a reference which makes it look like they're part of the state of an object. It's an unfortunate part of the design of the Calendar class that to access the values of different fields, you need to call get with a field number, specified as one of those constants, as shown in other answers:

Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);

请注意,该数字月份是基于0,所以在写这篇文章(四月份)的时间的月数为3。

Note that the month numbers are 0-based, so at the time of this writing (in April) the month number will be 3.

这是你的 Java语言设计的一个不幸的一部分可以的通过这种类型的前pressions,而不是引用静态成员(如常量)的唯一通过类型名称。

It's an unfortunate part of the design of the Java language that you can reference static members (such as constants) via expressions of that type, rather than only through the type name.

我的建议:


  • 如果您的IDE允许它(Eclipse一样),使前pressions如 c.YEAR 给出一个编译时错误 - 你最终会与更清晰code,如果你总是使用 Calendar.YEAR

  • 如果可能的话,使用乔达时间 - 一个Java的更好的日期/时间库。诚然,在Android上,你可能会有点空间受限,但如果你的应用程序做了很多的日期/时间处理的,它会为你节省很多麻烦。

  • If your IDE allows it (as Eclipse does), make expressions such as c.YEAR give a compile-time error - you'll end up with much clearer code if you always use Calendar.YEAR.
  • Where possible, use Joda Time - a much better date/time library for Java. Admittedly on Android you may be a bit space-constrained, but if your app does a lot of date/time manipulation, it would save you a lot of headaches.

这篇关于获取当前年份和月份产生奇怪的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆