Java:从日期获取月份整数 [英] Java: Get month Integer from Date
问题描述
如何从 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屋!