把日期字符串中的年月日提取出来

本文介绍了一个简单的日期解析器实现,该解析器能够从指定格式的字符串中提取年、月、日,并验证其有效性。

// pase_date_string.cpp : Defines the entry point for the console application.
//版权所有:吴建凰

#include "stdafx.h"
#include <iostream.h>

int monthday[12]={31,29,31,30,31,30,31,31,30,31,30,31};

bool parse_date_string(const char * date_string,int * year,int * month,int * day){
int len=0;
const char *str=date_string;
while(str[len])//计算日期字符串的长度
len++;
if(len<8 || len>10)
return false;
int date[3]={0};//存放格式为 月日年
len=0;
int i=0;
int temp=0;//临时变量,用于保存提取出来的数
bool err=false;
while(str[len]&& i<3 ){//把字符中的年月日提取出来
err=true;//先假设有错误
if(str[len]<='9' && str[len]>='0' ){//如果当前字符不是数字
temp=temp*10+str[len]-'0';//把字符数组转换成数字
err=false;//标记为没有错误
}
if(str[len]=='-' || str[len]=='/' || str[len+1]=='/0'){//把对应的数字提取出来了
if(temp>1000 && date[2]==0){//如果提起的是年
date[2]=temp;
}
else{
date[i++]=temp;
}
temp=0;//临时变量归位为0
}
else if(err){//假设没有被清除,即出现错误了
return false;
}
len++;
}
//计算二月的日期
if(date[2]&3 ){//date[2]&3 = date[2]%4
monthday[1]=28;

}
else{//为闰年
monthday[1]=29;
}
//判断提取的年月日是否出错
if(date[0]>12 || date[1]>monthday[date[0]] || date[2]<1000 ){
return false;
}
*year=date[2];
*month=date[0];
*day=date[1];
return true;//返回成功标志
}

int main(int argc, char* argv[])
{
int i=0;
int year;
int month;
int day;
if(parse_date_string("2009-9-8",&year,&month,&day)){
cout<<year<<"年"<<month<<"月"<<day<<"日"<<endl;
}
else
cout<<"日期格式错误"<<endl;
return 0;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值