【整理】Linux C/C++ 字符串时间对比大小

原创文章,转载请注明: 转载自勤奋的小青蛙
本文链接地址: 【整理】Linux C/C++ 字符串时间对比大小
#include <time.h>
time_t to_seconds(const char *date)
{
        struct tm storage={0,0,0,0,0,0,0,0,0};
        char *p=NULL;
        time_t retval=0;

        p=(char *)strptime(date,"%d-%b-%Y",&storage);
        if(p==NULL)
        {
                retval=0;
        }
        else
        {
                retval=mktime(&storage);
        }
        return retval;
}

int main()
{
   char *date1="20-JUN-2006";
   char *date2="21-JUN-2006";
   time_t d1=to_seconds(date1);
   time_t d2=to_seconds(date2);
   
   printf("date comparison: %s %s ",date1,date2);
   if(d1==d2) printf("equal\n");
   if(d2>d1)  printf("second date is later\n");
   if(d2<d1)  printf("seocnd date is earlier\n");
   return 0;
}

代码片段参考:

bool Utils::compareTradingDay(const char *compare_day, const char *today) {
	struct tm tm_time = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
	struct tm tm_time2 = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };

	std::cout << "compare_day = " << compare_day << std::endl;
	std::cout << "today = " << today << std::endl;

	strptime(compare_day, "%Y%m%d", &tm_time);
	time_t l_time1 = mktime(&tm_time);

	strptime(today, "%Y%m%d", &tm_time2);
	time_t l_time2 = mktime(&tm_time2);

	std::cout << "compare_day = " << l_time1 << std::endl;
	std::cout << "today = " << l_time2 << std::endl;
	
	
	if (l_time1 >= l_time2) {
		std::cout << "date is earlier than today!" << std::endl;
		return true; // 大于当前日期
	} else {
		std::cout << "date is later than today!" << std::endl;
		return false; // 小于当前日期
	}
}
原创文章,转载请注明: 转载自勤奋的小青蛙
本文链接地址: 【整理】Linux C/C++ 字符串时间对比大小

文章的脚注信息由WordPress的wp-posturl插件自动生成



|2|left
打赏

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: