Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.util.Date and getYear()

Tags:

java

date

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?

like image 586
johngoche9999 Avatar asked Feb 11 '12 19:02

johngoche9999


People also ask

What can I use instead of getYear?

Date has the getyear() method that returns a value that is subtracted from the year 1900. But this method was deprecated a long while ago in Java. Instead, we can use the LocalDate class available in java. time as the preferred method to do any Date and Time operations.

What is Java Util date?

The java. util. Date class represents a particular moment in time, with millisecond precision since the 1st of January 1970 00:00:00 GMT (the epoch time). The class is used to keep coordinated universal time (UTC).


1 Answers

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); 
like image 149
fasholaide Avatar answered Oct 03 '22 12:10

fasholaide