java.util.Date and getYear()

JavaDate

Java Problem Overview


I am having the following problem in Java (I see some people are having a similar problem in JavaScript but I'm using Java)

System.out.println(new Date().getYear());
System.out.println(new GregorianCalendar().getTime().getYear());
System.out.println(this.sale.getSaleDate().getYear());
System.out.println(this.sale.getSaleDate().getMonth());
System.out.println(this.sale.getSaleDate().getDate());

returns

I/System.out( 4274): 112
I/System.out( 4274): 112
I/System.out( 4274): 112
I/System.out( 4274): 1
I/System.out( 4274): 11

I don't understand the 112 bit which I thought would have been 2012. What's going on? Is the java.util.Date class unusable? I am storing this as a field in several of my classes to store a date and time. What should I do?

Java Solutions


Solution 1 - Java

In addition to all the comments, I thought I might add some code on how to use java.util.Date, java.util.Calendar and java.util.GregorianCalendar according to the javadoc.

//Initialize your Date however you like it.
Date date = new Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
//Add one to month {0 - 11}
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);

Solution 2 - Java

According to javadocs:

@Deprecated
public int getYear()

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.

Returns: the year represented by this date, minus 1900.

See Also: Calendar

So 112 is the correct output. I would follow the advice in the Javadoc or use JodaTime instead.

Solution 3 - Java

Use date format

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(datetime);
SimpleDateFormat df = new SimpleDateFormat("yyyy");
year = df.format(date);

Solution 4 - Java

Don't use Date, use Calendar:

// Beware: months are zero-based and no out of range errors are reported
Calendar date = new GregorianCalendar(2012, 9, 5);
int year = date.get(Calendar.YEAR);  // 2012
int month = date.get(Calendar.MONTH);  // 9 - October!!!
int day = date.get(Calendar.DAY_OF_MONTH);  // 5

It supports time as well:

Calendar dateTime = new GregorianCalendar(2012, 3, 4, 15, 16, 17);
int hour = dateTime.get(Calendar.HOUR_OF_DAY);  // 15
int minute = dateTime.get(Calendar.MINUTE);  // 16
int second = dateTime.get(Calendar.SECOND);  // 17

Solution 5 - Java

The java documentation suggests to make use of Calendar class instead of this deprecated way Here is the sample code to set up the calendar object

Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());

Here is the sample code to get the year, month, etc.

System.out.println(calendar.get(Calendar.YEAR));
System.out.println(calendar.get(Calendar.MONTH));

Calendar also has support for many other useful information like, TIME, DAY_OF_MONTH, etc. Here the documentation listing all of them Please note that the month are 0 based. January is 0th month.

Solution 6 - Java

tl;dr

LocalDate.now()       // Capture the date-only value current in the JVM’s current default time zone.
         .getYear()   // Extract the year number from that date.

>2018

java.time

Both the java.util.Date and java.util.Calendar classes are legacy, now supplanted by the java.time framework built into Java 8 and later.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;  

If you want only the date without time-of-day, use LocalDate. This class lacks time zone info but you can specify a time zone to determine the current date.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate localDate = LocalDate.now( zoneId );

You can get the various pieces of information with getYear, getMonth, and getDayOfMonth. You will actually get the year number with java.time!

int year = localDate.getYear();

>2016

If you want a date-time instead of just a date, use ZonedDateTime class.

ZonedDateTime zdt = ZonedDateTime.now( zoneId ) ;



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 the java.time classes.

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 & Java 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.

Solution 7 - Java

Yup, this is in fact what's happening. See also the Javadoc:

> Returns: > the year represented by this date, minus 1900.

The getYear method is deprecated for this reason. So, don't use it.

Note also that getMonth returns a number between 0 and 11. Therefore, this.sale.getSaleDate().getMonth() returns 1 for February, instead of 2. While java.util.Calendar doesn't add 1900 to all years, it does suffer from the off-by-one-month problem.

You're much better off using JodaTime.

Solution 8 - Java

Java 8 LocalDate class is another option to get the year from a java.util.Date,

int year = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date)).getYear();

Another option is,

int year = Integer.parseInt(new SimpleDateFormat("yyyy").format(date));

Solution 9 - Java

Year.now()

There's an easier way to use the java.time library in Java 8+. The expression:

java.time.Year.now().getValue()

returns the current year as a four-digit int, using your default time zone. There are lots of options for different time ZoneIds, Calendars and Clocks, but I think this is what you will want most of the time. If you want the code to look cleaner (and don't need any other java.time.*.now() functions), put:

import static java.time.Year.now;

at the top of your file, and call:

now().getValue()

as needed.

Solution 10 - Java

There are may ways of getting day, month and year in java.

You may use any-

	Date date1 = new Date();
	String mmddyyyy1 = new SimpleDateFormat("MM-dd-yyyy").format(date1);
	System.out.println("Formatted Date 1: " + mmddyyyy1);
	
	
	
	Date date2 = new Date();
	Calendar calendar1 = new GregorianCalendar();
	calendar1.setTime(date2);
	int day1   = calendar1.get(Calendar.DAY_OF_MONTH);
	int month1 = calendar1.get(Calendar.MONTH) + 1;	// {0 - 11}
	int year1  = calendar1.get(Calendar.YEAR);
	String mmddyyyy2 = ((month1<10)?"0"+month1:month1) + "-" + ((day1<10)?"0"+day1:day1) + "-" + (year1);
	System.out.println("Formatted Date 2: " + mmddyyyy2);
	
	
	
	LocalDateTime ldt1 = LocalDateTime.now();  
    DateTimeFormatter format1 = DateTimeFormatter.ofPattern("MM-dd-yyyy");  
    String mmddyyyy3 = ldt1.format(format1);  
    System.out.println("Formatted Date 3: " + mmddyyyy3);  
	
    
    
    LocalDateTime ldt2 = LocalDateTime.now();
    int day2 = ldt2.getDayOfMonth();
    int mont2= ldt2.getMonthValue();
    int year2= ldt2.getYear();
    String mmddyyyy4 = ((mont2<10)?"0"+mont2:mont2) + "-" + ((day2<10)?"0"+day2:day2) + "-" + (year2);
	System.out.println("Formatted Date 4: " + mmddyyyy4);
	
	
	
	LocalDateTime ldt3 = LocalDateTime.of(2020, 6, 11, 14, 30); // int year, int month, int dayOfMonth, int hour, int minute
	DateTimeFormatter format2 = DateTimeFormatter.ofPattern("MM-dd-yyyy");  
	String mmddyyyy5 = ldt3.format(format2);   
	System.out.println("Formatted Date 5: " + mmddyyyy5); 
	  
    
	
	Calendar calendar2 = Calendar.getInstance();
	calendar2.setTime(new Date());
	int day3  = calendar2.get(Calendar.DAY_OF_MONTH); // OR Calendar.DATE
	int month3= calendar2.get(Calendar.MONTH) + 1;
	int year3 = calendar2.get(Calendar.YEAR);
	String mmddyyyy6 = ((month3<10)?"0"+month3:month3) + "-" + ((day3<10)?"0"+day3:day3) + "-" + (year3);
	System.out.println("Formatted Date 6: " + mmddyyyy6);
	
	
	
	Date date3 = new Date();
	LocalDate ld1 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date3)); // Accepts only yyyy-MM-dd
	int day4  = ld1.getDayOfMonth();
	int month4= ld1.getMonthValue();
	int year4 = ld1.getYear();
	String mmddyyyy7 = ((month4<10)?"0"+month4:month4) + "-" + ((day4<10)?"0"+day4:day4) + "-" + (year4);
	System.out.println("Formatted Date 7: " + mmddyyyy7);
	
	
	
	Date date4 = new Date();
	int day5   = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getDayOfMonth();
	int month5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getMonthValue();
	int year5  = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getYear();
	String mmddyyyy8 = ((month5<10)?"0"+month5:month5) + "-" + ((day5<10)?"0"+day5:day5) + "-" + (year5);
	System.out.println("Formatted Date 8: " + mmddyyyy8);
	
	
	
	Date date5 = new Date();
	int day6   = Integer.parseInt(new SimpleDateFormat("dd").format(date5));
	int month6 = Integer.parseInt(new SimpleDateFormat("MM").format(date5));
	int year6  = Integer.parseInt(new SimpleDateFormat("yyyy").format(date5));
	String mmddyyyy9 = ((month6<10)?"0"+month6:month6) + "-" + ((day6<10)?"0"+day6:day6) + "-" + (year6);
	System.out.println("Formatted Date 9: " + mmddyyyy9);

Solution 11 - Java

This behavior is documented in the java.util.Date -class documentation:

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

It is also marked as deprecated. Use java.util.Calendar instead.

Solution 12 - Java

        try{ 
int year = Integer.parseInt(new Date().toString().split("-")[0]); 
} 
catch(NumberFormatException e){
}

Much of Date is deprecated.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionjohngoche9999View Question on Stackoverflow
Solution 1 - JavafasholaideView Answer on Stackoverflow
Solution 2 - JavaPeter SvenssonView Answer on Stackoverflow
Solution 3 - JavaMosiurView Answer on Stackoverflow
Solution 4 - JavaKonstantin SpirinView Answer on Stackoverflow
Solution 5 - JavaAmol DixitView Answer on Stackoverflow
Solution 6 - JavaBasil BourqueView Answer on Stackoverflow
Solution 7 - JavajqnoView Answer on Stackoverflow
Solution 8 - JavaGeorgios SyngouroglouView Answer on Stackoverflow
Solution 9 - JavaWilliam H. HooperView Answer on Stackoverflow
Solution 10 - JavaiamfnizamiView Answer on Stackoverflow
Solution 11 - JavaesajView Answer on Stackoverflow
Solution 12 - Javauser287853View Answer on Stackoverflow