Java:从Date获取月份整数

时间:2011-08-24 22:18:01

标签: java date calendar

如何从Date对象(java.util.Date)获取整数作为整数?

7 个答案:

答案 0 :(得分:267)

java.util.Date date= new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);

答案 1 :(得分:39)

java.time (Java 8)

You can also use the java.time package in Java 8 and convert your java.util.Date object to a java.time.LocalDate object and then just use the getMonthValue() method.

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

Note that month values are here given from 1 to 12 contrary to cal.get(Calendar.MONTH) in adarshr's answer which gives values from 0 to 11.

But as Basil Bourque said in the comments, the preferred way is to get a Month enum object with the LocalDate::getMonth method.

答案 2 :(得分:13)

如果你使用 Java 8 日期api,你可以直接把它放在一行!

LocalDate today = LocalDate.now();
int month = today.getMonthValue();

答案 3 :(得分:7)

约达时间

或者,使用Joda-Time DateTime类。

//convert date to datetime
DateTime datetime = new DateTime(date);
int month = Integer.parseInt(datetime.toString("MM"))

...或...

int month = dateTime.getMonthOfYear();

答案 4 :(得分:5)

TL;博士

myUtilDate.toInstant()                          // Convert from legacy class to modern. `Instant` is a point on the timeline in UTC.
          .atZone(                              // Adjust from UTC to a particular time zone to determine date. Renders a `ZonedDateTime` object. 
              ZoneId.of( "America/Montreal" )   // Better to specify desired/expected zone explicitly than rely implicitly on the JVM’s current default time zone.
          )                                     // Returns a `ZonedDateTime` object.
          .getMonthValue()                      // Extract a month number. Returns a `int` number.

java.time详细信息

Ortomala Lokni使用The Answer

java.time是正确的。并且你应该使用java.time,因为它是对旧的java.util.Date/.Calendar类的巨大改进。请参阅java.time上的Oracle Tutorial

我将添加一些代码,展示如何使用java.time而不考虑java.util.Date,以便在开始使用新代码时使用。

简而言之,使用java.time Instant是UTC时间轴上的一个时刻。应用时区(ZoneId)以获得ZonedDateTime

Month类是一个复杂的enum来表示一般的月份。该枚举有方便的方法,如获取本地化的名称。请放心,java.time中的月份数字是理智的,1-12,而不是java.util.Date/.Calendar中的零基础无意义(0-11)。

要获取当前日期时间,time zone至关重要。在任何时候,世界各地的日期相同。因此,如果接近月末/月初,那么全世界的月份就不一样了。

ZoneId zoneId = ZoneId.of( "America/Montreal" );  // Or 'ZoneOffset.UTC'.
ZonedDateTime now = ZonedDateTime.now( zoneId );
Month month = now.getMonth(); 
int monthNumber = month.getValue(); // Answer to the Question.
String monthName = month.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH );

关于 java.time

java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.DateCalendar和& SimpleDateFormat

现在位于Joda-Timemaintenance mode项目建议迁移到java.time类。

要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310

您可以直接与数据库交换 java.time 对象。使用符合JDBC driver或更高版本的JDBC 4.2。不需要字符串,不需要java.sql.*类。

从哪里获取java.time类?

ThreeTen-Extra项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如IntervalYearWeekYearQuartermore

答案 5 :(得分:3)

如果你不能使用Joda时间,你仍然生活在黑暗的世界:)(Java 5或更低版本)你可以享受这个:

注意:请确保您的日期已经完成,格式为:dd / MM / YYYY

/**
Make an int Month from a date
*/
public static int getMonthInt(Date date) {

    SimpleDateFormat dateFormat = new SimpleDateFormat("MM");
    return Integer.parseInt(dateFormat.format(date));
}

/**
Make an int Year from a date
*/
public static int getYearInt(Date date) {

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");
    return Integer.parseInt(dateFormat.format(date));
}

答案 6 :(得分:0)

Date mDate = new Date(System.currentTimeMillis());
mDate.getMonth() + 1

返回值从0开始,因此您应该在结果中添加一个。

相关问题