Linux时间戳、日期转换函数

Linux时间戳、日期转换函数:

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

time_t date_to_timestamp(char *date, char *pfmt)
{
        struct tm t;
        strptime(date, pfmt, &t);
        time_t tt = mktime(&t);
        return tt;
}

string  timestamp_to_date(time_t tt)
{
        struct tm *t = localtime(&tt);
        char dateBuf[128];
        snprintf(dateBuf, sizeof(dateBuf), "%04d-%02d-%02d %02d:%02d:%02d", t->tm_year+1900,
                t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);

        string date(dateBuf);
        return date;
}

int main()
{
        /*
        time_t tt = 1372225160;
        string date = timestamp_to_date(tt);
        cout<<"date:"<<date.c_str()<<endl;
        */

        char *date = "2013-06-26 13:39:20";
	char *pfmt = "%Y-%m-%d %H:%M:%S";
        time_t tt = date_to_timestamp(date, pfmt);
        cout<<"time_t:"<<tt<<endl;
        
        return 0;
}


你可能感兴趣的:(Linux时间戳、日期转换函数)