gpt4 book ai didi

validation - 如何在 C++ 中验证 “YYYY: MM: DD HH:MM:SS” 格式的时间?

转载 作者:行者123 更新时间:2023-12-04 00:51:37 24 4
gpt4 key购买 nike

我想验证以字符串格式给出的时间为“YYYY-MM-DD HH:MM:SS”,并想检查哪个是最新日期。

我可以将给定的字符串转换为秒,并按如下方式进行比较。

std::string dateStr1 = "2016-06-31 02:00:58"; // June 31 2016 does not exist
std::string dateStr2 = "02:00:00";

std::istringstream date_s(dateStr1);
struct tm date_c;
date_s >> std::get_time( &date_c, "%Y-%m-%d %H:%M:%S" );
std::time_t seconds1 = std::mktime( & date_c );

std::istringstream date_s2( "2001-10-01 02:10:00" );
struct tm date_c2;
date_s2 >> std::get_time( &date_c2, "%Y-%m-%d %H:%M:%S" );
std::time_t seconds2 = std::mktime( & date_c2 );

if(seconds1 > seconds2){
cout<<" Seconds1 is greater "<<seconds1<<endl;
}else{
cout<<" Seconds2 is greater "<<seconds2<<endl;
}

答案:Seconds1 大于 1467334858

问题:这个方法转换了一个不存在的日期。(dateStr1 中给出的日期不存在,但 mktime() 为该日期腾出时间。)

如何判断一个日期是否存在?

最佳答案

来自cppreference documentation of mktime :

If the conversion is successful, the time object is modified. All fields of time are updated to fit their proper ranges. time->tm_wday and time->tm_yday are recalculated using information available in other fields.

您可以使用它来检查日期是否有效。如果无效,tm 结构将由 mktime 修改:

std::string dateStr1 = "2016-06-31 02:00:58"; // June 31 2016 does not exist
std::string dateStr2 = "02:00:00";

std::istringstream date_s(dateStr1);
struct tm date_c, date_c_cmp;
date_s >> std::get_time( &date_c, "%Y-%m-%d %H:%M:%S" );
date_c_cmp = date_c; // store original to compare later
std::time_t seconds1 = std::mktime( & date_c );
if(date_c.tm_year != date_c_cmp.tm_year // compare with original
|| date_c.tm_mon != date_c_cmp.tm_mon
|| date_c.tm_mday != date_c_cmp.tm_mday
|| date_c.tm_hour != date_c_cmp.tm_hour
|| date_c.tm_min != date_c_cmp.tm_min
|| date_c.tm_sec != date_c_cmp.tm_sec)
std::cout << "invalid" << std::endl;

std::istringstream date_s2( "2001-10-01 02:10:00" );
struct tm date_c2;
date_s2 >> std::get_time( &date_c2, "%Y-%m-%d %H:%M:%S" );
std::time_t seconds2 = std::mktime( & date_c2 );

if(seconds1 > seconds2){
std::cout<<" Seconds1 is greater "<<seconds1<<std::endl;
}else{
std::cout<<" Seconds2 is greater "<<seconds2<<std::endl;
}

关于validation - 如何在 C++ 中验证 “YYYY: MM: DD HH:MM:SS” 格式的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39447921/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com