获取月份的最后一天 [英] Get last day of Month

查看:123
本文介绍了获取月份的最后一天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于获取最后一个月的日期,我写了此函数

For getting last date of month I have written this function

/**
 * @param month integer value of month
 * @param year integer value of month
 * @return last day of month in MM/dd/YYYY format
 */
private static String getDate(int month, int year) {
    Calendar calendar = Calendar.getInstance();
    // passing month-1 because 0-->jan, 1-->feb... 11-->dec
    calendar.set(year, month - 1, 1);
    calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
    Date date = calendar.getTime();
    DateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/YYYY");
    return DATE_FORMAT.format(date);
}

为所有输入工作正常,当月份为12月,即getDate(12,2012)返回12/31/2013,但它应该返回12/31/2012。
请解释一下行为和解决方案。

for all the inputs its working fine with one exception when the month is December, i.e. getDate(12, 2012) returns 12/31/2013 but it should return 12/31/2012. Please explain the behavior and solution too.

推荐答案

更改 YYYY yyyy

Change YYYY to yyyy

DateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy");  

YYYY 错误 dateformat

这篇关于获取月份的最后一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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