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

Month is not printed from a date - Java DateFormat(月份不是从日期打印的 - 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 get week of year for given a date(java获取给定日期的一年中的一周)
Get the number of days, weeks, and months, since Epoch in Java(获取自 Java 中的 Epoch 以来的天数、周数和月数)
Is there a good way to get the date of the coming Wednesday?(有什么好方法可以得到即将到来的星期三的日期吗?)
Calendar view for Android GingerBread and before (APIlt;11)(Android GingerBread 及之前的日历视图 (API11))
How to save and retrieve Date in SharedPreferences(如何在 SharedPreferences 中保存和检索日期)
Why is the month changed to 50 after I added 10 minutes?(为什么我加了 10 分钟后月份变成了 50?)