获得指定时间的前一个时间的分组

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;



// /*******************************************************
/// @brief 获得指定时间的开始结束时间列表
///
/// @param: tTime 时间戳
/// @param: iInterval 时间分段间隔(分钟)
/// @param: iOffset 偏移量(分钟)
///
/// @returns:   vec[0]:starttime  vec[1]:endtime vec[2]:sleeptime
// *******************************************************/
vector<string> getTimeList(time_t tTime, int iInterval, int iOffset)
{
    vector<string> timelist;

    time_t newTime = tTime - iOffset * 60;
    struct tm newTm;

    localtime_r(&newTime, &newTm);
    struct tm endTime = newTm;
    endTime.tm_min = int(newTm.tm_min / iInterval) * iInterval;
    endTime.tm_sec = 0;

    char buf[64];
    strftime(buf, 64, "%Y-%m-%d %H:%M:%S", &endTime);
    timelist.insert(timelist.begin(), 1, buf);

    time_t startTime = mktime(&endTime) - iInterval * 60;
    localtime_r(&startTime, &newTm);
    struct tm sTime = newTm;
    sTime.tm_min = int(newTm.tm_min / iInterval) * iInterval;
    sTime.tm_sec = 0;

    memset(buf, 0, sizeof(buf));
    strftime(buf, 64, "%Y-%m-%d %H:%M:%S", &sTime);
    timelist.insert(timelist.begin(), 1, buf);

    stringstream str;
    str<<mktime(&endTime) + iInterval * 60 + iOffset * 60 - tTime;
    timelist.push_back(str.str());

    return timelist;
}

// /*******************************************************
/// @brief 字符串转换为时间
///
/// @param: a_strTimeStr
///
/// @returns:  时间戳
// *******************************************************/
time_t timeStr2Timestamp(const string &a_strTimeStr)
{
    string::size_type pos = a_strTimeStr.find("-");
    string normalTime = "";
    if(pos != string::npos)
        normalTime = a_strTimeStr;
    else
    {
        normalTime = a_strTimeStr.substr(0, 4) + "-" + a_strTimeStr.substr(4,2) + "-" + \
            a_strTimeStr.substr(6,2) + " " + a_strTimeStr.substr(8,2) + \ ":" + a_strTimeStr.substr(10,2) + ":" + a_strTimeStr.substr(12,2); } tm time; strptime(normalTime.c_str(), "%Y-%m-%d %H:%M:%S", &time); return mktime(&time); } int main() { time_t now = time(NULL); vector<string> timelist = getTimeList(now, 20, 5); cout<<"now is "<<now<<",start:"<<timelist[0]<<", "<<"end:"<<timelist[1]<<",sleep "<<timelist[2]<<" seconds"<<endl; cout<<"@1 str to time is "<<timeStr2Timestamp("20160922173000")<<endl; cout<<"@2 str to time is "<<timeStr2Timestamp("2016-09-22 17:30:00")<<endl; return 0; }

 

posted on 2016-09-22 10:56  霏霏暮雨  阅读(211)  评论(0编辑  收藏  举报

导航