您的位置:首页 > 其它

日期计算函数:已知当前日期,求过了一段时间后的日期。

2017-05-22 14:25 267 查看

函数的功能是,根据当前日期,计算过了一段时间后的日期。

1. 流程图:



2.函数实现:

/**
* Method called to check if the date is valid.
* short duration: unit is day.
* short[] curData: current date, format is YYMMDD
* byte [] expData: store the expected date, format is YYMMDD
* Return value: false if fail, else succeed.
*/
private static boolean vGetExpectDate(short[] curDate, short duration, short [] expDate)
{
short year;
short month;
short day;
short days_left;
short day_add = 0;

// Assign the real date to year, month, day and hour
year = curDate[0];
month = curDate[1];
day = curDate[2];

day_add = duration;

// days add to year
while(day_add > (days_left = sDaysToNextYear(year, month, day)))
{
// come to the 1st day in 1st month of the next year.
year++;
month = 1;
day = 1;
day_add -= days_left;
}

// days add to month
while(day_add > (days_left = sDaysToNextMonth(year, month, day)))
{
month++;
day = 1;
day_add -= days_left;
}

// days add to day
day += day_add;

// store the expected date into the workbuf.
expDate[0] = year;
expDate[1] = month;
expDate[2] = day;

return true;
}

private static short sDaysToNextYear(byte year, byte month, byte day)
{
byte days_Feb;
byte days_month;
short ret;

switch(month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days_month = 31;
break;
case 4:
case 6:
case 9:
case 11:
days_month = 30;
break;
case 2:
// Here assumes the year is 20xx, so if the year is leap or not depends on the last byte xx.
if(0 == (year % 4))
days_month = 29;
else
days_month = 28;
break;
default:
break;
}

ret = days_month - day + 1;
month++;

switch(month)
{
case 2:
ret += days_Feb;
case 3:
ret += 31;
case 4:
ret += 30;
case 5:
ret += 31;
case 6:
ret += 30;
case 7:
ret += 31;
case 8:
ret += 31;
case 9:
ret += 30;
case 10:
ret += 31;
case 11:
ret += 30;
case 12:
ret += 31;
default:
break;
}

return ret;
}

private static short sDaysToNextMonth(byte year, byte month, byte day)
{
byte days_month;

switch(month)
{
case 1:
days_month = 31;
break;
case 2:
// Here assumes the year is 20xx, so if the year is leap or not depends on the last byte xx.
if(0 == (year % 4))
days_month = 29;
else
days_month = 28;
break;
case 3:
days_month = 31;
break;
case 4:
days_month = 30;
break;
case 5:
days_month = 31;
break;
case 6:
days_month = 30;
break;
case 7:
days_month = 31;
break;
case 8:
days_month = 31;
break;
case 9:
days_month = 30;
break;
case 10:
days_month = 31;
break;
case 11:
days_month = 30;
break;
case 12:
days_month = 31;
break;
default:
break;
}

return (days_month - day + 1);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  日期计算函数