求帮忙写个程序 JAVA C++都行
发布网友
发布时间:2022-12-28 16:53
我来回答
共2个回答
热心网友
时间:2023-07-07 07:02
主要类
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtils {
public String nextDate(String cur) throws Exception {
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
try {
Date curDate = formater.parse(cur);
Calendar cal = Calendar.getInstance();
if (cal.get(Calendar.YEAR) < 1900 || cal.get(Calendar.YEAR) > 2200) {
throw new Exception("年份必须在1900到2200年之间");
}
if (cal.get(Calendar.MONTH) < 1 || cal.get(Calendar.MONTH) > 12) {
throw new Exception("月份必须在1到12月之间");
}
if (cal.get(Calendar.DATE) < 1) {
throw new Exception("每月日期不得小于1");
} else {
switch (cal.get(Calendar.MONTH)) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (cal.get(Calendar.DATE) > 31) {
throw new Exception(cal.get(Calendar.MONTH) + "月份只有31天");
}
break;
case 4:
case 6:
case 9:
case 11:
if (cal.get(Calendar.DATE) > 30) {
throw new Exception(cal.get(Calendar.MONTH) + "月份只有30天");
}
break;
case 2:
if ((cal.get(Calendar.YEAR) % 4 == 0 && cal.get(Calendar.YEAR) % 100 != 0) || (cal.get(Calendar.YEAR) % 100 == 0 && cal.get(Calendar.YEAR) % 400 == 0)) {
if (cal.get(Calendar.DATE) > 29) {
throw new Exception(cal.get(Calendar.YEAR) + "为闰年,2月份只有29天");
}
} else {
if (cal.get(Calendar.DATE) > 28) {
throw new Exception(cal.get(Calendar.YEAR) + "为闰年,2月份只有28天");
}
}
break;
default:
break;
}
}
if (cal.get(Calendar.MONTH) < 1 || cal.get(Calendar.MONTH) > 12) {
throw new Exception("月份必须在1到12月之间");
}
cal.setTime(curDate);
cal.add(Calendar.DATE, 1);
return formater.format(cal.getTime());
} catch (ParseException e) {
throw e;
}
}
}
测试类
import org.junit.Assert;
import org.junit.Test;
public class DateTest {
@Test
public void getCurDate() {
DateUtils = new DateUtils();
String result = null;
try {
result = .nextDate("1901-15-12");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(result);
Assert.assertNotNull(result);
}
}
热心网友
时间:2023-07-07 07:03
java.util.Calendar 处理,很方便,有方法加