#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