简体   繁体   English

从java.util.Date获取Year

[英]get Year from java.util.Date

I have a date column in a Cassandra column family. 我在Cassandra列族中有一个日期列。 When I retrieve data from this CF using datastax java API, this date object can be taken as a java.util.Date object. 当我使用datastax java API从此CF检索数据时,可以将此日期对象视为java.util.Date对象。

It has a getYear() method but it is deprecated. 它有一个getYear()方法但不推荐使用。 The corresponding javadoc says: 相应的javadoc说:

As of JDK version 1.1, replaced by Calendar.get(Calendar.YEAR) - 1900. 从JDK 1.1版开始,由Calendar.get(Calendar.YEAR) - 1900取代。

How can I get the year, month, day attributes from this date object properly? 如何正确获取此日期对象的年,月,日属性?

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 ; 正如javadocs中提到的那样;

@Deprecated public int getYear() Deprecated. @Deprecated public int getYear()已过时。 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. 从JDK版本1.1开始,由Calendar.get(Calendar.YEAR) - 1900取代。返回一个值,该值是从包含或以此Date对象表示的时刻开始的年份减去1900的结果,如当地时区。 Returns: the year represented by this date, minus 1900. 返回:此日期表示的年份减去1900。

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

use LocalDate object in java8 在java8中使用LocalDate对象

Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int year  = localDate.getYear();
int month = localDate.getMonthValue();
int day   = localDate.getDayOfMonth();

To retrieve the date & time fields you can use this code: 要检索日期和时间字段,您可以使用以下代码:

DateFormat.getDateTimeInstance().getCalendar().get(DateFormat.MONTH_FIELD)

Just replace MONTH_FIELD with one somehting else like "DAY_OF_WEEK_FIELD" to retrieve the day of the week (I think '1' stands for monday) or "MINUTE_FIELD" for the current minute, etc. :) 只需用一个像“DAY_OF_WEEK_FIELD”这样的其他东西替换MONTH_FIELD来检索星期几(我认为'1'代表星期一)或当前分钟的“MINUTE_FIELD”等等:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM