如何获得特定日期某个地点的时区(偏移)?

时间:2012-09-03 15:58:04

标签: c++ datetime

我以UTC格式存储消息。因此,如果有人回顾上一条消息,我需要能够将时间戳转换为时间相对于时区的时间。我如何得到当时的时区?

例如,2012年9月3日,时区是PDT。当前时间偏差为-0700。我在9:06发了一条消息。 UTC的时间是16:06。

我将在2012年12月1日回复此消息。当前时区是PST。当前时间偏移为-0800。我查看了我在2012年9月3日发送的消息。如果我使用当前时间偏移从UTC转换回来,我得到8:06,这不是发送消息的时候。它是在9:06发送的。

因此,我需要一种方法来发现,在2012年9月3日,时区是PDT,而不是PST。

P.S。没有图书馆将是最好的,谢谢。

3 个答案:

答案 0 :(得分:3)

Boost Date_time这样做,这里只是我闲逛的例子(下面的代码):

edd@max:~/src/progs/C++$ g++ -o boost_posix_time_dst boost_posix_time_dst.cpp
edd@max:~/src/progs/C++$ ./boost_posix_time_dst 
DST ran from 2012-Mar-11 02:00:00 to 2012-Nov-04 02:00:00
DST shortcut PDT
DST name     Pacific Daylight Time
edd@max:~/src/progs/C++$ 

还有一些功能可以形成一个日期(2012年12月1日)并查看它是否在给定间隔内(由此处由DST开始和结束形成)。

我认为你也可以通过形成一个日期并检查isDST()布尔值来获得它。

我的简短程序如下。您需要csv文件的本地副本,其中a)在Boost源中,b)在许多处理时区的网站上(例如Google的第一次或第二次点击在CERN找到它):

#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/posix_time_io.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>  
#include <boost/date_time/local_time/local_time.hpp>     

using namespace boost::posix_time;
using namespace boost::gregorian;

int main(int argc, char **argv) {

  boost::local_time::tz_database tz;
  tz.load_from_file("/tmp/date_time_zonespec.csv");

  boost::local_time::time_zone_ptr tzp =
            tz.time_zone_from_region("America/Los_Angeles");    

  int year = 2012;
  boost::posix_time::ptime t1 = tzp->dst_local_start_time(year);
  boost::posix_time::ptime t2 = tzp->dst_local_end_time(year);
  std::cout << "DST ran from " << t1 << " to " << t2 << std::endl;
  std::cout << "DST shortcut " << tzp->dst_zone_abbrev() << std::endl;
  std::cout << "DST name     " << tzp->dst_zone_name() << std::endl;

}

答案 1 :(得分:2)

如果它是一个简单的C++应用程序,在执行期间不需要使用单独的时区,那么您只需使用localtime即可获得包含时区的共享struct tm *引用调用它的特定time_t的信息。如果您的系统配置了PST的时区,那么当您调用localtime时,它将使用太平洋时区信息进行显示 - 使用2012年1月1日(格林威治标准时间)和2012年6月1日的示例:< / p>

time_t def_time = 1325376000;
struct tm *a_tim = localtime(&def_time);
printf("%s %ld %d\n", a_tim->tm_zone, a_tim->tm_gmtoff, a_tim->tm_isdst);
def_time = 1338505200;
a_tim = localtime(&def_time);
printf("%s %ld %d\n", a_tim->tm_zone, a_tim->tm_gmtoff, a_tim->tm_isdst);

在我的系统(TZ = Europe / Dublin)上显示:

GMT 0 0
IST 3600 1

通过使用America / Los_Angeles覆盖TZ环境变量,我得到:

PST -28800 0
PDT -25200 1

即。系统能够很好地确定时区名称,偏离GMT以及夏令时是否与UTC时间戳有效。

编辑:尝试使用posix提供的时区例程同时在C / C ++程序中使用多个时区是非常糟糕的,如果你处于那种状态,我肯定会推荐使用boost,因为它很快溶液

答案 2 :(得分:0)

只知道当前的偏移量不足以告诉你一年中另一个时间同一地点的偏移量;有很多地方只有一年中的部分时间共享一个时区(例如中欧和阿尔及利亚,或美国东部和哥伦比亚)。

最简单的解决方法是将时区与消息一起存储。