gpt4 book ai didi

java - 月份不是从日期打印的 - Java DateFormat

转载 作者:搜寻专家 更新时间:2023-10-30 21:39:58 24 4
gpt4 key购买 nike

如何从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(因为月份是从零开始的;demo)

关于java - 月份不是从日期打印的 - Java DateFormat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19036033/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com