在Calendar.set()上检测到无效日期 [英] Detect invalid date on Calendar.set()

查看:215
本文介绍了在Calendar.set()上检测到无效日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此方法,该方法返回一个由其字段(DAY,MONTH,YEAR)之一更改的Date()。

I have this method that returns me a Date() changed by one of it's "fields" (DAY, MONTH, YEAR).

public static Date getDateChanged(Date date, int field, int value) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.set(field, value);
    return cal.getTime();
}

但是,当该字段时,cal.set()无法给出异常我们正在尝试设置与该日期不兼容的日期。因此,在这种情况下:

However, cal.set() is unable to give an exception when the field we are trying to set is not compatible with the date in question. So, in this case:

Date date = new Date();
date = getDateChanged(date, Calendar.DAY_OF_MONTH, 29); 
date = getDateChanged(date, Calendar.MONTH, 1); // feb

日期最后是15年1月3日,因为Calendar.set( )检测到不能在第29天设置2月,因此自动将日期设置为下一个可能的日期(我认为这是例程的工作方式)。

date is, in the end, 01/03/15, because Calendar.set() detects that February can't be set with day 29, so automatically set's date to the next possible day (I thinks this is how the routine works).

这还不错,但是就我而言,

This is not so bad, however, in my case,

我想检测出我的日期'试图建造是不可能的,然后然后开始递减一天,因此在这种情况下,我想要实现的目标是15年2月28日,我该怎么做?

I want to detect that the date I'm trying to build is impossible and then start decrementing the day, so in this case what I'm trying to achieve is 28/02/15, how can I do this?

示例:


15年2月29日===> 15年2月28日

29/02/15 ===> 28/02/15


推荐答案

您可以使用 cal.getActualMaximum(Calendar.DAY_OF_MONTH)来查找日历实例在给定月份的最长天数。

You can use cal.getActualMaximum(Calendar.DAY_OF_MONTH) to find the maximum days in the given month for your calendar instance.

通过这种方式,您可以处理自己上面提到的情况。

This way, you can handle the case you mentioned above yourself.

也请在此处查看答案:在特定年份的特定月份的天数?

Also see the answer here: Number of days in particular month of particular year?

这篇关于在Calendar.set()上检测到无效日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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