-
#include <iostream>
-
#include <time.h>
-
#include <sys/time.h>
-
-
-
using namespace std;
-
-
int main()
-
{
-
time_t t; //秒时间
-
tm* local; //本地时间
-
tm* gmt; //格林威治时间
-
char buf[128]= {0};
-
-
t = time(NULL); //获取目前秒时间
-
local = localtime(&t); //转为本地时间
-
strftime(buf, 64, "%Y-%m-%d %H:%M:%S", local);
-
std::cout << buf << std::endl;
-
-
gmt = gmtime(&t);//转为格林威治时间
-
strftime(buf, 64, "%Y-%m-%d %H:%M:%S", gmt);
-
std::cout << buf << std::endl;
-
-
-
struct timeval tv;
-
struct timezone tz;
-
gettimeofday(&tv, &tz);
-
t = tv.tv_sec;
-
-
local = localtime(&t); //转为本地时间
-
strftime(buf, 64, "%Y-%m-%d %H:%M:%S", local);
-
std::cout << buf << std::endl;
-
-
gmt = gmtime(&t);//转为格林威治时间
-
strftime(buf, 64, "%Y-%m-%d %H:%M:%S", gmt);
-
std::cout << buf << std::endl;
-
-
-
}
输出
2017-04-19 19:26:45
2017-04-19 11:26:45
2017-04-19 19:26:45
2017-04-19 11:26:45
$ date 实际时间
2017年 04月 19日 星期三 19:26:47 CST
可以看到
http://blog.csdn.net/ncepubdtb/article/details/38899505
-
1、常用的时间存储方式
-
-
1)time_t类型,这本质上是一个长整数,表示从1970-01-01 00:00:00到目前计时时间的秒数,如果需要更精确一点的,可以使用timeval精确到毫秒。
-
-
2)tm结构,这本质上是一个结构体,里面包含了各时间字段
-
-
struct tm {
-
int tm_sec;
-
int tm_min;
-
int tm_hour;
-
int tm_mday;
-
int tm_mon;
-
int tm_year;
-
int tm_wday;
-
int tm_yday;
-
int tm_isdst;
-
};
-
-
其中tm_year表示从1900年到目前计时时间间隔多少年,如果是手动设置值的话,tm_isdst通常取值-1。
-
-
2、常用的时间函数
-
-
time_t time(time_t *t);
-
char *asctime(const struct tm *tm);
-
char *ctime(const time_t *timep);
-
struct tm *gmtime(const time_t *timep);
-
struct tm *localtime(const time_t *timep);
-
time_t mktime(struct tm *tm);
-
int gettimeofday(struct timeval *tv, struct timezone *tz);
-
double difftime(time_t time1, time_t time2);
-
-
-
3、时间与字符串的转换
-
-
需要包含的头文件如下
-
-
#include
-
#include
-
#include
-
#include
-
-
1)unix/windows下时间转字符串参考代码
-
-
time_t t;
-
tm* local;
-
tm* gmt;
-
char buf[128]= {0};
-
-
t = time(NULL);
-
local = localtime(&t);
-
strftime(buf, 64, "%Y-%m-%d %H:%M:%S", local);
-
std::cout << buf << std::endl;
-
-
gmt = gmtime(&t);
-
strftime(buf, 64, "%Y-%m-%d %H:%M:%S", gmt);
-
std::cout << buf << std::endl;
-
-
-
-
2)unix字符串转时间参考代码
-
-
-
tm tm_;
-
time_t t_;
-
char buf[128]= {0};
-
-
strcpy(buf, "2012-01-01 14:00:00");
-
strptime(buf, "%Y-%m-%d %H:%M:%S", &tm_);
-
tm_.tm_isdst = -1;
-
t_ = mktime(&tm_);
-
t_ += 3600;
-
-
tm_ = *localtime(&t_);
-
strftime(buf, 64, "%Y-%m-%d %H:%M:%S", &tm_);
-
std::cout << buf << std::endl;
-
-
-
-
3)由于windows下没有strptime函数,所以可以使用scanf来格式化
-
-
-
time_t StringToDatetime(char *str)
-
{
-
tm tm_;
-
int year, month, day, hour, minute,second;
-
sscanf(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_);
-
return t_;
-
}
阅读(3957) | 评论(0) | 转发(0) |