服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - C++时间戳转化操作实例分析【涉及GMT与CST时区转化】

C++时间戳转化操作实例分析【涉及GMT与CST时区转化】

2021-05-13 12:25jihite C/C++

这篇文章主要介绍了C++时间戳转化操作,结合实例形式分析了C++时间戳转换与显示操作的原理与具体实现技巧,涉及GMT与CST时区转化,需要的朋友可以参考下

本文实例讲述了C++时间戳转化操作。分享给大家供大家参考,具体如下:

问题由来

时间戳转换(时间戳:自 1970 年1月1日(00:00:00 )至当前时间的总秒数。)

?
1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
#include <time.h>
int main(int argc, const char * argv[])
{
  time_t t;
  struct tm *p;
  t=1408413451;
  p=gmtime(&t);
  char s[80];
  strftime(s, 80, "%Y-%m-%d %H:%M:%S", p);
  printf("%d: %s\n", (int)t, s);
}

结果

?
1
1408413451   2014-08-19 01:57:1408384651

可是利用命令在linux终端计算的结果不一

?
1
2
[###t]$ date -d @1408413451
Tue Aug 19 09:57:31 CST 2014

通过比较发现,两者正好差8个小时,CST表示格林尼治时间,通过strftime()函数可以输出时区,改正如下

?
1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
#include <time.h>
int main(int argc, const char * argv[])
{
  time_t t;
  struct tm *p;
  t=1408413451;
  p=gmtime(&t);
  char s[80];
  strftime(s, 80, "%Y-%m-%d %H:%M:%S::%Z", p);
  printf("%d: %s\n", (int)t, s);
}

结果

?
1
1408413451: 2014-08-19 01:57:31::GMT

深究

GMT(Greenwich Mean Time)代表格林尼治标准时间。十七世纪,格林威治皇家天文台为了海上霸权的扩张计画而进行天体观测。1675年旧皇家观测所正式成立,通过格林威治的子午线作为划分地球东西两半球的经度零度。观测所门口墙上有一个标志24小时的时钟,显示当下的时间,对全球而言,这里所设定的时间是世界时间参考点,全球都以格林威治的时间作为标准来设定时间,这就是我们耳熟能详的「格林威治标准时间」(Greenwich Mean Time,简称G.M.T.)的由来。

CST却同时可以代表如下 4 个不同的时区:

?
1
2
3
4
Central Standard Time (USA) UT-6:00
Central Standard Time (Australia) UT+9:30
China Standard Time UT+8:00
Cuba Standard Time UT-4:00

可见,CST可以同时表示美国,澳大利亚,中国,古巴四个国家的标准时间。

好了两者差8个小时(CST比GMT晚/大8个小时),GMT+8*3600=CST,代码如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
#include <time.h>
int main(int argc, const char * argv[])
{
  time_t t;
  struct tm *p;
  t=1408413451;
  p=gmtime(&t);
  char s[80];
  strftime(s, 80, "%Y-%m-%d %H:%M:%S::%Z", p);
  printf("%d: %s\n", (int)t, s);
  t=1408413451 + 28800;
  p=gmtime(&t);
  strftime(s, 80, "%Y-%m-%d %H:%M:%S", p);
  printf("%d: %s\n", (int)t, s);
  return 0;
}

结果

?
1
2
1408413451: 2014-08-19 01:57:31::GMT
1408442251: 2014-08-19 09:57:31

linux平台

?
1
Tue Aug 19 09:57:31 CST 2014

希望本文所述对大家C++程序设计有所帮助。

延伸 · 阅读

精彩推荐