繁体   English   中英

C ++与字符串日期比较

[英]C++ compare to string dates

我需要比较2个字符串日期,以查看一个日期是否晚于另一个日期。 两个日期的日期格式位于底部。 我可以重新安排这个最简单的事情。 我有提升但不一定是,我已经通过这么多的例子,似乎无法将我的大脑包围起来让它发挥作用。 提前谢谢基本上我想要的

2012-12-06 14:28:51

if (date1 < date2) {
 // do this
}
else {
 // do that
}  

看起来您使用的日期格式已经按字典顺序排列,标准字符串比较将起作用,例如:

std::string date1 = "2012-12-06 14:28:51";
std::string date2 = "2012-12-06 14:28:52";
if (date1 < date2) {
    // ...
}
else {
    // ...
}

使用这种格式时,您需要确保间距和标点符号是一致的,特别是像2012-12-06 9:28:51这样的2012-12-06 9:28:51会破坏比较。 2012-12-06 09:28:51虽然会奏效

你很幸运 - 你的日期已经采用正确的格式进行标准字符串比较并获得正确的结果。 所有部件从最重要到最不重要,你使用24小时。

如果这些是std::string您可以使用<就像您在样本中一样。 如果它们是C风格的字符数组字符串,请使用strcmp

strcmp()返回一个整数值,表示字符串之间的关系:

 result = strcmp( string1, string2 ); 
 if( result > 0 )  strcpy( tmp, "greater than" );
 else if( result < 0 )  strcpy( tmp, "less than" );

零值表示两个字符串相等。 大于零的值表示不匹配的第一个字符在str1中的值大于在str2中的值; 小于零的值表示相反。

#include <string.h>
#include <stdio.h>

char string1[] = "2012-12-06 14:28:51";
char string2[] = "2011-12-06 14:28:51";

int main( void )
{
   char tmp[20];
   int result;

   printf( "Compare strings:\n   %s\n   %s\n\n\n", string1, string2 );
   result = strcmp( string1, string2 );

   if( result > 0 )        strcpy( tmp, "greater than" );
   else if( result < 0 )   strcpy( tmp, "less than" );
   else    strcpy( tmp, "equal to" );

   printf( "   strcmp:   String 1 is %s string 2\n\n", tmp );

   return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM