首页 > 编程语言 > 详细

c++ 字符串时间格式转换为时间 判断有效期

时间:2019-05-11 18:00:54      阅读:778      评论:0      收藏:0      [点我收藏+]

转载:https://www.cnblogs.com/maphc/p/3462952.html

#include <iostream>
#include <time.h>
using namespace std;


time_t str_to_time_t(const string& ATime, const string& AFormat = "%d-%d-%d %d:%d:%d")
{
    struct tm tm_Temp;
    time_t time_Ret;
    try
    {
        int i = sscanf(ATime.c_str(), AFormat.c_str(),// "%d/%d/%d %d:%d:%d" ,       
            &(tm_Temp.tm_year),
            &(tm_Temp.tm_mon),
            &(tm_Temp.tm_mday),
            &(tm_Temp.tm_hour),
            &(tm_Temp.tm_min),
            &(tm_Temp.tm_sec));

        tm_Temp.tm_year -= 1900;
        tm_Temp.tm_mon--;
        //如果精确到秒就把下面四行注释掉;如果精确到天就把下面四行代码放开
        //tm_Temp.tm_hour = 0;
        //tm_Temp.tm_min = 0;
        //tm_Temp.tm_sec = 0;
        //tm_Temp.tm_isdst = 0;
        time_Ret = mktime(&tm_Temp);
        return time_Ret;
    }
    catch (...) {
        return 0;
    }
}

time_t NowTime()
{
    time_t t_Now = time(0);
    struct tm* tm_Now = localtime(&t_Now);
    //如果精确到秒就把下面四行注释掉;如果精确到天就把下面四行代码放开
    //tm_Now->tm_hour = 0;
    //tm_Now->tm_min = 0;
    //tm_Now->tm_sec = 0;
    return  mktime(tm_Now);
}

bool IsValidTime(const time_t& AEndTime, const time_t& ANowTime)
{
    return (AEndTime >= ANowTime);
}


int main()
{
    string sEndTime = "2019-5-11 17:38:59";

    time_t t_Now = NowTime();
    time_t t_End = str_to_time_t(sEndTime);
    if (IsValidTime(t_End, t_Now)) {
        cout<< "有效日期" << endl;
    }
    else {
        cout << "时间过期" << endl;
    }
    return 0;
}

 

c++ 字符串时间格式转换为时间 判断有效期

原文:https://www.cnblogs.com/chechen/p/10849405.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!