时间格式处理学习指南

发布时间 2023-10-20 16:18:43作者: White_Sheep

前置芝士

h:m:s转为seconds

int pto (string time){
	int h,m,s;
	sscanf(time.c_str(),"%d:%d:%d",&h,&m,&s);
	return h*3600+m*60+s;
}

seconds转为h:m:s

string sto(int seconds){
	int h=seconds/3600;
	seconds%=3600;
	int m=seconds/60;
	int s=seconds%=60;
	char buffer[9];
	snprintf(buffer,sizeof(buffer),"%02d:%02d:%02d",h,m,s);
	return string(buffer);
}

判断日期非法性

(闰年的条件)

一:能被4整除,但不能被100整除的年份(例如2008是闰年,1900不是闰年)

二:能被400整除的年份(例如2000年)也是闰年。

三.闰年2月份有29天,一年有366天。

四.平年2月分有28天,一年有365天。

[java]

boolean check(String str){
        SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        try{
            df.setLenient(false);//false:为严格,true:为不严格
            df.parse(str);
        }catch (Exception e){
            return false;
        }
        return true;
    }
void solve(){
String str1="2000-2-29";
System.out.println(check(str1));}