月份不会从日期打印 – Java DateFormat
如何从java中的日期获取月份:
DateFormat inputDF = new SimpleDateFormat("mm/dd/yy"); Date date1 = inputDF.parse("9/30/11"); Calendar cal = Calendar.getInstance(); cal.setTime(date1); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); int year = cal.get(Calendar.YEAR); System.out.println(month+" - "+day+" - "+year);
此代码返回日期和年份,但不是月份。
输出:
0 - 30 - 2011
这是因为您的格式不正确:本月需要"MM/dd/yy"
,因为"mm"
表示分钟:
DateFormat inputDF = new SimpleDateFormat("MM/dd/yy"); Date date1 = inputDF.parse("9/30/11"); Calendar cal = Calendar.getInstance(); cal.setTime(date1); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); int year = cal.get(Calendar.YEAR); System.out.println(month+" - "+day+" - "+year);
印刷品8 - 30 - 2011
(因为月份是零基础; 演示 )
首先,您在日期格式中使用了mm
, 根据Javadocs , 这是“分钟” 。 您将分钟设置为9
,而不是月份。 看起来月份默认为0(1月)。
使用MM
(大写’M’)来解析月份。 然后,您将看到8
,因为在Calendar
月份从0开始,而不是1 。 加1
以获得所需的9
。
格列高利历和朱利安历的一年中的第一个月是1月,即0
// MM is month, mm is minutes DateFormat inputDF = new SimpleDateFormat("MM/dd/yy");
然后
int month = cal.get(Calendar.MONTH) + 1; // To shift range from 0-11 to 1-12
如果您阅读SimpleDateFormat
javadoc ,您会注意到mm
是几分钟。 你需要MM
一个月。
DateFormat inputDF = new SimpleDateFormat("MM/dd/yy");
否则,格式不会读取month
字段并假定值为0
。
月份格式应为MM
而不是mm
DateFormat inputDF = new SimpleDateFormat("MM/dd/yy");
是时候有人提供现代答案了。 当问题在2013年被提出并且仍然正确时,其他答案是很好的答案。 今天没有理由为什么你应该与旧的,过时的和同时臭名昭着的麻烦的SimpleDateFormat
类斗争。 java.time
,现代Java日期和时间API,可以更好地使用:
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("M/d/yy"); LocalDate date1 = LocalDate.parse("9/30/11", inputFormatter); System.out.println(date1);
这打印
2011-09-30
LocalDate
类表示没有时间的日期,正是您所需要的,它比旧类Date
和Calendar
更精确地匹配您的需求。
与DateTimeFormatter
使用的格式模式字符串类似于SimpleDateFormat
的格式模式字符串,存在一些差异。 您可以使用大写字母MM
来要求两位数的月份(如9月份的09)或单个M
来允许用一位或两位数字来写月份。 同样dd
或d
表示每月的某一天。 yy
表示两位数的年份,用2000基础解释,即从2000年到2099年(不适用于我的生日)。
链接 : Oracle教程Trail:Date Time解释如何使用java.time
。
尝试使用MM
代替mm
: –
DateFormat inputDF = new SimpleDateFormat("MM/dd/yy"); Date date1 = inputDF.parse("9/30/11"); Calendar cal = Calendar.getInstance(); cal.setTime(date1); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); int year = cal.get(Calendar.YEAR); System.out.println(month+" - "+day+" - "+year);
索引从0开始,打印月份为8
或尝试: –
int month = cal.get(Calendar.MONTH) + 1;
mm
是分钟,在指定格式时使用MM
。
Calendar cal = Calendar.getInstance(); cal.setTime(date1); int month = cal.get(Calendar.MONTH);// returns month value index starts from 0