Java:从日期获取月份整数

发布于 2024-12-01 10:01:37 字数 59 浏览 0 评论 0 原文

如何从 Date 对象 (java.util.Date) 获取整数形式的月份?

How do I get the month as an integer from a Date object (java.util.Date)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

绳情 2024-12-08 10:01:37
java.util.Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
java.util.Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
月下凄凉 2024-12-08 10:01:37

java.time (Java 8)

您还可以使用 java.time 包 并转换您的 java.util.Date 对象到 java.time.LocalDate 对象,然后只需使用 getMonthValue()< /a> 方法。

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

请注意,这里给出的月份值是从 1 到 12,这与 adarshr 的答案中的 cal.get(Calendar.MONTH) 相反,它给出了从 0 到 11 的值。

但正如 Basil Bourque 在评论中所说,首选方法是获取 Month 带有 LocalDate::getMonth 方法。

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.

时光瘦了 2024-12-08 10:01:37

如果你使用Java 8日期api,直接一行即可获取!

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

If you use Java 8 date api, you can directly get it in one line!

LocalDate today = LocalDate.now();
int month = today.getMonthValue();
紧拥背影 2024-12-08 10:01:37

Joda-Time

或者,使用 Joda-Time DateTime 类。

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

…或者…

int month = dateTime.getMonthOfYear();

Joda-Time

Alternatively, with the Joda-Time DateTime class.

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

…or…

int month = dateTime.getMonthOfYear();
能否归途做我良人 2024-12-08 10:01:37

tl;dr

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 使用 java.time 是正确的。您应该使用java.time,因为它比旧的java.util.Date/.Calendar 类有了巨大的改进。请参阅 java.time 上的 Oracle 教程

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

简而言之,使用 java.time...即时 是 UTC 时间线上的一个时刻。应用时区 (ZoneId )来获取 ZonedDateTime

月份 class 是一个复杂的 enum 来表示一般月份。该枚举具有方便的方法,例如获取本地化名称。请放心,java.time 中的月份数字是正常的,即 1-12,而不是 java.util.Date/.Calendar 中的从零开始的废话 (0-11)。

要获取当前日期时间,时区至关重要。在任何时候,世界各地的日期都相同。因此,如果接近月底/月初,世界各地的月份是不一样的。

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 及更高版本中。这些类取代了麻烦的旧遗留日期时间类,例如java.util.Date, 日历,& SimpleDateFormat

Joda-Time 项目,现已在 维护模式,建议迁移到java.time 类。

要了解更多信息,请参阅 Oracle 教程 。并在 Stack Overflow 上搜索许多示例和解释。规范为 JSR 310

您可以直接与数据库交换java.time对象。使用符合 JDBC 驱动程序 jeps/170" rel="noreferrer">JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* 类。

从哪里获取 java.time 类?

ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是 java.time 未来可能添加的内容的试验场。您可能会在这里找到一些有用的类,例如 Interval YearWeekYearQuarter更多

tl;dr

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 Details

The Answer by Ortomala Lokni for using java.time is correct. And you should be using java.time as it is a gigantic improvement over the old java.util.Date/.Calendar classes. See the Oracle Tutorial on java.time.

I'll add some code showing how to use java.time without regard to java.util.Date, for when you are starting out with fresh code.

Using java.time in a nutshell… An Instant is a moment on the timeline in UTC. Apply a time zone (ZoneId) to get a ZonedDateTime.

The Month class is a sophisticated enum to represent a month in general. That enum has handy methods such as getting a localized name. And rest assured that the month number in java.time is a sane one, 1-12, not the zero-based nonsense (0-11) found in java.util.Date/.Calendar.

To get the current date-time, time zone is crucial. At any moment the date is not the same around the world. Therefore the month is not the same around the world if near the ending/beginning of the month.

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

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

时光与爱终年不遇 2024-12-08 10:01:37

如果您无法使用 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));
}

If you can't use Joda time and you still live in the dark world :) ( Java 5 or lower ) you can enjoy this :

Note: Make sure your date is allready made by the format : 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));
}
∝单色的世界 2024-12-08 10:01:37

如果我们使用 java.time.LocalDate api,我们可以在单行中获取整数月份数字:

import java.time.LocalDate;
...
int currentMonthNumber = LocalDate.now().getMonthValue(); //OR
LocalDate scoringDate = LocalDate.parse("2022-07-01").getMonthValue(); //for String date

例如今天的日期是 2022 年 7 月 29 日,输出将为 7。

If we use java.time.LocalDate api, we can get month number in integer in single line:

import java.time.LocalDate;
...
int currentMonthNumber = LocalDate.now().getMonthValue(); //OR
LocalDate scoringDate = LocalDate.parse("2022-07-01").getMonthValue(); //for String date

For example today's date is 29-July-2022, output will be 7.

呆橘 2024-12-08 10:01:37
Date mDate = new Date(System.currentTimeMillis());
mDate.getMonth() + 1

返回值从0开始,所以应该给结果加1。

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

The returned value starts from 0, so you should add one to the result.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文