unix time stamp和常规时间相互转换的C++代码

         从unix time stamp到常规时间:

#include <iostream>
#include <ctime>
using namespace std;

void unixTime2Str(int n, char strTime[], int bufLen)
{
    struct tm tm = *localtime((time_t *)&n);
    strftime(strTime, bufLen - 1, "%Y-%m-%d %H:%M:%S", &tm);
	strTime[bufLen - 1] = '\0';
}

int main(void)
{
	char strTime[100] = {0};
	int now = 1444401700;
	unixTime2Str(now, strTime, sizeof(strTime));
	cout << strTime << endl;

    return 0;
}
         结果为:2015-10-09 22:41:40


         再看常规时间到unix stamp time的转换:

#include <iostream>
#include <ctime>
using namespace std;

time_t strTime2unix(char timeStamp[])
{
    struct tm tm;
    memset(&tm, 0, sizeof(tm));
    
    sscanf(timeStamp, "%d-%d-%d %d:%d:%d", 
           &tm.tm_year, &tm.tm_mon, &tm.tm_mday,
           &tm.tm_hour, &tm.tm_min, &tm.tm_sec);

    tm.tm_year -= 1900;
    tm.tm_mon--;

    return mktime(&tm);
}

int main()
{
	char timeStamp[100] = "2015-10-09 22:41:40";
    time_t t = strTime2unix(timeStamp);
    cout << t << endl;
    
	// additional
	cout << ctime(&t) << endl;

    return 0;
} 
         结果为:

1444401700
Fri Oct 09 22:41:40 2015


        OK, 无需多说。



你可能感兴趣的:(unix time stamp和常规时间相互转换的C++代码)