已知一个日期和一个月份数,想得到相加后的日期!!!急
已知一个日期的字符串 例2004-01-02 和一个月数例4个月
如何才能得到相加后的日期 2004-05-02
月数有可能是33个月等情况
[解决办法]
逢12进1啊,
yyyy-mm-dd
x
yyyy+(int)(mm+x)/12
不过对二月好像不好使,如今天是 3.31日,加一个月的话,应该是4月30呢还是5月1呢?
[解决办法]
可定义一个进位标志 如果月份相加之和大于12则 取余数为月份 商加到年份里
[解决办法]
如果只考虑年月那只是大致的年和月
如果考虑天数可以建立一个天数列表,进行查表
[解决办法]
#include <iostream>
#include "stdlib.h"
using namespace std;
int count[3];
void ParseStr(char* str)
{
char *p = new char[strlen(str)+1];
strcpy(p, str);
char *q = NULL;
int i(0);
while(p)
{
q = strchr(p, '-');
if(q)
{
*q++ = 0;
count[i++] = atoi(p);
p = q;
}
else
{
count[i] = atoi(p);
break;
}
}
}
void Print()
{
char szTmp[20] ={0};
sprintf(szTmp, "%d-%02d-%02d", count[0], count[1], count[2]);
cout < <szTmp < <endl;
}
int main()
{
char str[] = "2004-01-02";
ParseStr(str);
cout < <"please enter month count" < <endl;
int month;
cin>>month;
if(month <0)
{
cout < <"error" < <endl;
return -1;
}
else
{
int i = count[1] + month;
count[0] += i/12;
count[1] += i%12;
Print();
}
return 0;
}
#include <iostream>#include "stdlib.h"using namespace std;int count[3];void ParseStr(char* str){ char *p = new char[strlen(str)+1]; strcpy(p, str); char *q = NULL; int i(0); while(p) { q = strchr(p, '-'); if(q) { *q++ = 0; count[i++] = atoi(p); p = q; } else { count[i] = atoi(p); break; } } delete p; p = NULL;}void Print(){ char szTmp[20] ={0}; sprintf(szTmp, "%d-%02d-%02d", count[0], count[1], count[2]); cout<<szTmp<<endl;}int main(){ char str[] = "2004-01-02"; ParseStr(str); cout<<"please enter month count"<<endl; int month; cin>>month; if(month<0) { cout<<"error"<<endl; return -1; } else { int i = count[1] + month; count[0] += i/12; count[1] += i%12; Print(); } return 0;}
[解决办法]
以33个月为例: 假设当前2000-10-1
x=33;
month=month+x; //变为2000-43-1
year=year+month/12; //变为2003-43-1
month=month%12; //变为2003-7-1
[解决办法]
//比较烂的。不能和jerry的比.int main(){ char cTime[]={"2004-01-02"}; char cDestTim[50]={0}; //大一点; int month=33; char tem[10]; char *p=strtok (cTime,"-"); int tem1=atoi(p); //记录年; p=strtok(NULL,"-"); //此时是月份: int tem2=atoi(p)+month; if(tem2>12) tem1+= tem2/12; tem2=tem2%12; itoa(tem1, tem, 10); strcpy(cDestTim, tem ); strcat(cDestTim, "-"); int len1=strlen(tem)+1; itoa(tem2, tem, 10); strcpy(cDestTim+len1, tem); strcat(cDestTim, "-"); int len2=strlen(tem)+1+len1; //获得日的数字; p=strtok(NULL,"-"); strcpy(cDestTim+len2, p); puts(cDestTim); return 0;}
[解决办法]
碰到闰月怎么处理?
[解决办法]
还要考虑一下闰年的问题
[解决办法]
碰到闰月,变一下day即可,因为是月份相加
[解决办法]
考虑闰年的情况还有2月份的特殊处理