Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 java.util.Date object.

It has a getYear() 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?

like image 328
Chamila Wijayarathna Avatar asked Dec 15 '14 17:12

Chamila Wijayarathna


People also ask

What can I use instead of getYear in Java?

As of JDK version 1.1, replaced by Calendar. get(Calendar.

Is Java Util date deprecated?

util. Date has some serious design flows, from the day it was introduced. Many of its methods were deprecated since Java 1.1 and ported to (abstract) java. util.


3 Answers

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.

like image 149
Semih Eker Avatar answered Oct 03 '22 05:10

Semih Eker


A good option is to use date format as follows:

SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy");
Date             date = sdf1.parse(datetime);
String           year = sdf2.format(date);
like image 22
Rakesh KR Avatar answered Oct 03 '22 06:10

Rakesh KR


use LocalDate object in java8

Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int year  = localDate.getYear();
int month = localDate.getMonthValue();
int day   = localDate.getDayOfMonth();
like image 43
Ammar Bozorgvar Avatar answered Oct 03 '22 04:10

Ammar Bozorgvar