C++ 时间戳转化(涉及 GMT CST 时区转化)

发表于:2016-9-28 10:03

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:jihite    来源:51Testing软件测试网采编

  问题由来
  时间戳转换(时间戳:自 1970 年1月1日(00:00:00 )至当前时间的总秒数。)
  #include
  #include 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: %sn", (int)t, s);
  }
  结果
  1408413451      2014-08-19 01:57:1408384651
  可是利用命令在linux终端计算的结果不一
  [###t]$ date -d @1408413451
  Tue Aug 19 09:57:31 <strong>CST</strong> 2014
  通过比较发现,两者正好差8个小时,CST表示格林尼治时间,通过strftime()函数可以输出时区,改正如下
  #include
  #include 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: %sn", (int)t, s);
  }
  结果
  1408413451: 2014-08-19 01:57:31::<strong>GMT
  </strong>
  深究
  GMT(Greenwich Mean Time)代表格林尼治标准时间。十七世纪,格林威治皇家天文台为了海上霸权的扩张计画而进行天体观测。1675年旧皇家观测所正式成立,通过格林威治的子午线作为划分地球东西两半球的经度零度。观测所门口墙上有一个标志24小时的时钟,显示当下的时间,对全球而言,这里所设定的时间是世界时间参考点,全球都以格林威治的时间作为标准来设定时间,这就是我们耳熟能详的「格林威治标准时间」(Greenwich Mean Time,简称G.M.T.)的由来。
  CST却同时可以代表如下 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,代码如下
  #include
  #include 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: %sn", (int)t, s);
  t=1408413451 + 28800;
  p=gmtime(&t);
  strftime(s, 80, "%Y-%m-%d %H:%M:%S", p);
  printf("%d: %sn", (int)t, s);
  return 0;
  }
  结果
  1408413451: 2014-08-19 01:57:31::GMT
  1408442251: 2014-08-19 09:57:31
  linux平台
  Tue Aug 19 09:57:31 CST 2014
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号