Java:从日期获取月份整数 [英] Java: Get month Integer from Date

查看:27
本文介绍了Java:从日期获取月份整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

java.time (Java 8)

您也可以使用 java.time在 Java 8 中打包并转换您的java.util.Date 对象到 java.time.LocalDate 对象,然后只使用 getMonthValue() 方法.

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

请注意,与 adarshr 的答案中的 cal.get(Calendar.MONTH) 给出的值从 0 到 11 不同,此处给出的月份值从 1 到 12.

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.

但正如 Basil Bourque 在评论中所说的,首选方式是获取 Month 枚举对象,带有 LocalDate::getMonth 方法.

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

这篇关于Java:从日期获取月份整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆