建议看这篇<a target=_blank href="http://blog.csdn.net/educast/article/details/17239735">C++时间与字符串转换 </a>,本人只是为方便使用和修改后记录一下。
vs2013社区版可以直接跑,顺便一提,strptime反正我这边没有,其所编写的类似函数不错。
</pre><pre class="cpp" name="code">#include "stdafx.h"
#include <time.h>
#include <string.h>
#include <iostream>
using namespace std;
int main()
{
time_t t; //秒时间
tm* local = new tm; //本地时间
tm* gmt = new tm; //格林威治时间
char buf[128] = { 0 };
t = time(NULL); //获取目前秒时间
localtime_s(local,&t); //转为本地时间
strftime(buf, 64, "%Y-%m-%d %H:%M:%S", local);
std::cout << buf << std::endl;
gmtime_s(gmt,&t);//转为格林威治时间
strftime(buf, 64, "%Y-%m-%d %H:%M:%S", gmt);
std::cout << buf << std::endl;
tm tm_;
time_t t_;
//char buf[128] = { 0 };
memset(buf, '\0',128);
strcpy_s(buf, "2012-01-01 14:00:00");
//strptime(buf, "%Y-%m-%d %H:%M:%S", &tm_); //将字符串转换为tm时间
time_t StringToDatetime(char *str, tm *tm_);
StringToDatetime(buf, &tm_);
tm_.tm_isdst = -1;
t_ = mktime(&tm_); //将tm时间转换为秒时间
t_ += 3600; //秒数加3600
localtime_s(&tm_,&t_);//输出时间
strftime(buf, 64, "%Y-%m-%d %H:%M:%S", &tm_);
std::cout << buf << std::endl;
getchar();
return 0;
}
time_t StringToDatetime(char *str,tm *tm_)
{
//tm tm_;
int year, month, day, hour, minute, second;
sscanf_s(str, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &second);
tm_->tm_year = year - 1900;
tm_->tm_mon = month - 1;
tm_->tm_mday = day;
tm_->tm_hour = hour;
tm_->tm_min = minute;
tm_->tm_sec = second;
tm_->tm_isdst = 0;
time_t t_ = mktime(tm_); //已经减了8个时区
return t_; //秒时间
}