题目已过期。
要求:
汇付的一笔试题,要求计算给定日期的前一天,日期格式"YYYYMMDD",不能使用Date、Calendar相关日期的操作方法
步骤:
1、先分割出给定日期的年、月、日,转成int类型
2、日期-1,分为1号和非1号
1号特殊操作,月份-1,需判断是否闰年,天数为最大(特殊月)
月份-1,需判断是否是减成了0,是的话年-1,月12,日31(跨年)
3、toString 年、月、日转String并补零
package net.leo.java.date;
/**
* 要求计算给定日期的前一天
* 不使用java API中的Date和Calendar
* 日期格式如“20101202”
*
* @title YesdayNoAPI
* @description
* @author cxh
* @version
* @create_date 2013-7-10
* @copyright (c)
*/
public class YesdayNoAPI {
// 2月天数
private int MAXDAYS_FEBRUARY;
private int year, month, day;
public static void main(String[] args) {
String todayStr = "00100101";
System.out.println("today is:" + todayStr);
YesdayNoAPI ins = new YesdayNoAPI();
ins.getYesday(todayStr);
System.out.println(ins.parseString());
}
/**
* 分割年月日
*
* @description
* @author cxh
* @param todayStr
*/
private void split(String todayStr) {
year = Integer.valueOf(todayStr.substring(0, 4));
month = Integer.valueOf(todayStr.substring(4, 6));
day = Integer.valueOf(todayStr.substring(6));
}
/**
* 获取前一天
*
* @description
* @author cxh
* @param todayStr
*/
public void getYesday(String todayStr) {
split(todayStr);
// 天数-1
if (day == 1) {
decMonth();
} else {
day -= 1;
}
}
/**
* 月-1 说明天数为1号
*
* @description
* @author cxh
*/
private void decMonth() {
switch (--month) {
// 跨年
case 0:
--year;
month = 12;
day = 31;
break;
case 2:
// 润平判断
isLeapYear();
day = MAXDAYS_FEBRUARY;
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
day = 31;
break;
default:
day = 30;
break;
}
}
/**
* 判断是否闰年 赋值2月天数
*
* @description
* @author cxh
*/
private void isLeapYear() {
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
MAXDAYS_FEBRUARY = 29;
} else {
MAXDAYS_FEBRUARY = 28;
}
}
/**
* toString
*
* @description
* @author cxh
* @return
*/
private String parseString() {
String dayStr = "" + day;
String monthStr = "" + month;
String yearStr = "" + year;
// 补0
if (day < 10) {
dayStr = "0" + day;
}
if (month < 10) {
monthStr = "0" + month;
}
for (int i = yearStr.length(); i < 4; i++) {
yearStr = "0" + yearStr;
}
return "yesday is:" + yearStr + monthStr + dayStr;
}
}
结果:
情况1:遇到2月
today is:20100301
yesday is:20100228
情况2:遇到跨年
today is:20100101
yesday is:20091231
情况3:遇到跨世纪
today is:00100101
yesday is:00091231