Chamila Wijayarathna Chamila Wijayarathna - 3 years ago 293
Java Question

get Year from java.util.Date

I have a date column in a Cassandra column family. When I retrieve data from this CF using datastax java API, this date object can be taken as a


It has a
method but it is deprecated. The corresponding javadoc says:

As of JDK version 1.1, replaced by Calendar.get(Calendar.YEAR) - 1900.

How can I get the year, month, day attributes from this date object properly?

Answer Source

Could you try like tihs;

      // create a calendar
      Calendar cal = Calendar.getInstance();
      cal.setTime(datetime);  //use java.util.Date object as arguement
      // get the value of all the calendar date fields.
      System.out.println("Calendar's Year: " + cal.get(Calendar.YEAR));
      System.out.println("Calendar's Month: " + cal.get(Calendar.MONTH));
      System.out.println("Calendar's Day: " + cal.get(Calendar.DATE));

As mentioned in 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download