Getting current Year and Month resulting strange results

半腔热情 提交于 2019-12-05 12:05:53

问题


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

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


回答1:


Just to give a bit more background:

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

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

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

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.

My recommendations:

  • 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.



回答2:


Note MONTHS starts from 0..So if you need to map it to practical problems just add +1

int month=c.get(Calendar.MONTH)+1;



回答3:


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

   System.out.println(year);
   System.out.println(month);



回答4:


Calendar c= Calendar.getInstance()
int cyear = c.get(Calendar.YEAR);//calender year starts from 1900 so you must add 1900 to the value recevie.i.e., 1990+112 = 2012
int cmonth = c.get(Calendar.MONTH);//this is april so you will receive  3 instead of 4.
int cday = c.get(Calendar.DAY_OF_MONTH);

refer this LINK




回答5:


tl;dr

YearMonth.now( 
    ZoneId.of( "America/Montreal" ) 
)

Details

The Answer by Jon Skeet is correct. You were accessing constants rather than interrogating your own object.

Here is an entirely different alternative, using modern date-time classes.

Avoid legacy date-time classes

The old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes.

YearMonth

If you are focused on the year and month without a date, without a time-of-day, and without a time zone, use the YearMonth class.

Rather than pass mere integer numbers around for year and for month, pass around objects of this class. Doing so provides type-safety, ensures valid values, and makes your code more self-documenting.

Determining the current year and month means determining the current date. And for that a time zone is crucial. For any given moment, the date varies around the globe by zone.

ZoneId z = ZoneId.of( "America/Montreal" );
YearMonth ym = YearMonth.now( z );

You can interrogate for its parts.

int year = ym.getYear();
int month = ym.getMonthValue();

This class offers handy methods such as telling you if this is a leap year. You can do math, such as adding/subtracting months/years. You can get a date for any day of this year-month. And more.

Month

Rather than mess around with a mere integer for month, I suggest you use the Month enum. This class has a dozen instances pre-defined, one for each month of the year. As mentioned above, using objects gives you type-safety, valid values, and self-documenting code.

Month m = ym.getMonth();

The class has helpful methods such as generating an localized string with the month’s name.


About java.time

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

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

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

Where to obtain the java.time classes?

  • Java SE 8 and SE 9 and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
    • See How to use….



回答6:


How to get current Year and Month.

        Calendar calendar = Calendar.getInstance();             
        int month = calendar.get(Calendar.MONTH) + 1;
        int year = calendar.get(Calendar.YEAR);

Very important to add 1 to get the correct month, because the first month value is 0:

        int month = calendar.get(Calendar.MONTH) + 1;

MONTH :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.



来源:https://stackoverflow.com/questions/10161637/getting-current-year-and-month-resulting-strange-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!