问题
星系炸弹
在X星系的广袤空间中漂浮着许多X星人造“炸弹”,用来作为宇宙中的路标。
每个炸弹都可以设定多少天之后爆炸。
比如:阿尔法炸弹2015年1月1日放置,定时为15天,则它在2015年1月16日爆炸。
有一个贝塔炸弹,2014年11月9日放置,定时为1000天,请你计算它爆炸的准确日期
解题
/**
* 星系炸弹
* 在X星系的广袤空间中漂浮着许多X星人造“炸弹”,用来作为宇宙中的路标。
*
* 每个炸弹都可以设定多少天之后爆炸。
*
* 比如:阿尔法炸弹2015年1月1日放置,定时为15天,则它在2015年1月16日爆炸。
*
* 有一个贝塔炸弹,2014年11月9日放置,定时为1000天,请你计算它爆炸的准确日期
* @param dateStr
* @param addDays
*/
public static void calculateDateAdditions(String dateStr, int addDays) throws ParseException {
// 定义正则校验输入
String regex = "\\d{4}[-]{1}\\d{2}[-]{1}\\d{2}";
if (!dateStr.matches(regex)){
System.out.println("时间输入格式不匹配 正确格式类似于 2022-07-13");
return;
}else{
if (addDays < 0){
System.out.println("天数不能小于 0");
return;
}
// 正常开始计算
// calendar 计算
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date parseDate = dateFormat.parse(dateStr);
Calendar instance = Calendar.getInstance();
instance.setTime(parseDate);
instance.add(Calendar.DAY_OF_MONTH, addDays);
System.out.println(instance.get(Calendar.YEAR)+" " + (instance.get(Calendar.MONTH) + 1)+ " " + instance.get(Calendar.DAY_OF_MONTH));
// 普通计算 使用一种即可
// String[] split = dateStr.split("-");
// Integer year = Integer.valueOf(split[0]);
// Integer mouth = Integer.valueOf(split[1]);
// Integer day = Integer.valueOf(split[2]);
//
// int[] mouthDay = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
//
// for (int i = 0; i < addDays; i++ ) {
// // 当前年
// if (year % 4 == 0 || year % 400 == 0){
// mouthDay[1] = 29;
// }else{
// mouthDay[1] = 28;
// }
//
// // 每次循环天数+1 月满了进入下一个月, 日重置
// day++;
// if (day > mouthDay[mouth-1]){
// day = 1;
// mouth++;
// }
// // 年满了进入下一年 月重置
// if (mouth > 12){
// mouth = 1;
// year++;
// }
// }
// System.out.println(year + " " + mouth + " " + day);
}
}