月份未从日期打印 - Java DateFormat [英] Month in not printed from a date - Java DateFormat

查看:119
本文介绍了月份未从日期打印 - 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 (因为月份为零; 演示

Prints 8 - 30 - 2011 (because months are zero-based; demo)

这篇关于月份未从日期打印 - Java DateFormat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆