c++字符串时间校验

#include "testcode.h"
#include <QtWidgets/QApplication>
#include <QDebug>

bool TimeAvailable(tm tm_)   //检查时间的合法性
{
    int year = tm_.tm_year;
    int month = tm_.tm_mon;
    int day = tm_.tm_mday;
    int hour = tm_.tm_hour;
    int minte = tm_.tm_min;
    int second = tm_.tm_sec;
    tm_.tm_isdst;
    if ((month == 0) || (month > 12) || (day == 0) || (hour > 24) || (minte > 59) || (second > 59)) //数值非法
    {
        return false;
    }

    switch (month)  //日数是否超限
    {
    case 1:
    case 3:
    case 5:
    case 7:
    case 8:
    case 10:
    case 12:    if (day > 31) return false; break;   //一个月31天
    case 4:
    case 6:
    case 9:
    case 11:    if (day > 30) return false; break;   //一个月30天
    case 2:
        if (((year % 4) == 0 && (year % 100) != 0) || ((year % 400) == 0))  //是否是闰年
        {
            if (day > 29)	//闰年2月29天
                return false;
            break;
        }
        else
        {
            if (day > 28)	//非闰年2月28天
                return false;
            break;
        }
    }
    return true;
}

time_t StringToDatetime(const char* str)
{
    tm tm_;
    int year, month, day, hour, minute, second;
    sscanf(str, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &second);
    tm_.tm_year = year /*- 1900*/;
    tm_.tm_mon = month /*- 1*/;
    tm_.tm_mday = day;
    tm_.tm_hour = hour;
    tm_.tm_min = minute;
    tm_.tm_sec = second;
    tm_.tm_isdst = 0;
    if (!TimeAvailable(tm_)) {
        qDebug() << "-----------------error time foramat";
        return -1;
    }
    qDebug() << "-----------------ok";
    time_t t_ = mktime(&tm_); //已经减了8个时区
    return t_; //秒时间
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
	/*TestCode w;
	w.show();*/
    /*char* str = new char[100];
    memset(str,0,strlen(str));
    int32_t num1 = 10;
    memcpy(str,&num1,sizeof(num1));
    int32_t num2;
    memcpy(&num2,str,4);
    qDebug() << "num2:"<< num2;*/
    StringToDatetime("2022-02-30 23:05:59");
    return a.exec();
}

输出:

-----------------error time foramat

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值