Month is not printed from a date - Java DateFormat(月份不是从日期打印的 - Java DateFormat)
问题描述
如何从java中的日期获取月份:
How to get month from a date in 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);
此代码返回日期和年份,但不返回月份.
This code return day and year but not month.
输出:
0 - 30 - 2011
推荐答案
这是因为你的格式不正确:你需要"MM/dd/yy"
这个月份,因为"mm"
是分钟:
This is because your format is incorrect: you need "MM/dd/yy"
for the month, because "mm"
is for minutes:
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
(因为月份是从零开始的;demo)
Prints 8 - 30 - 2011
(because months are zero-based; demo)
这篇关于月份不是从日期打印的 - Java DateFormat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:月份不是从日期打印的 - Java DateFormat


基础教程推荐
- 如何对 HashSet 进行排序? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01