我在Greg's good answer一直盯着一个几天了,和我考虑加入一些语法糖my timezone library:
namespace date
{
class zoneverter
{
const Zone* zp1_;
const Zone* zp2_;
public:
zoneverter(const Zone* z1, const Zone* z2)
: zp1_(z1)
, zp2_(z2)
{}
zoneverter(const Zone* z1, const std::string& z2)
: zoneverter(z1, locate_zone(z2))
{}
zoneverter(const std::string& z1, const Zone* z2)
: zoneverter(locate_zone(z1), z2)
{}
zoneverter(const std::string& z1, const std::string& z2)
: zoneverter(locate_zone(z1), locate_zone(z2))
{}
template <class Rep, class Period>
auto
operator<<(std::chrono::time_point<std::chrono::system_clock,
std::chrono::duration<Rep, Period>> tp) const
{
return zp1_->to_local(zp2_->to_sys(tp)).first;
}
};
} // namespace date
这增加了一个“流状物体”,它允许人们通过它传输一个std::chrono::time_point
将其从一个时区转换为另一种。这是一个非常简单的设备,除了添加一些语法糖之外,其他任何东西都不会丢失一些信息,从my timezone library。
它会像这样使用:
int
main()
{
// So things don't get overly verbose
using namespace date;
using namespace std::chrono;
// Set up the zone converters:
zoneverter nyc_from_utc{"America/New_York", "UTC"};
zoneverter anc_from_nyc{"America/Anchorage", "America/New_York"};
// Get the current time in New York and convert that to the current time in Anchorage
auto now_nyc = nyc_from_utc << system_clock::now();
auto now_anc = anc_from_nyc << now_nyc;
// Output the difference
std::cout << make_time(now_nyc - now_anc) << '\n';
}
这目前输出对我来说:
04:00:00.000000
我也不能确定这是否语法糖是不是足够好目前的语法来保证它的存在:
int
main()
{
// So things don't get overly verbose
using namespace date;
using namespace std::chrono;
// Set up the zones:
auto nyc_zone = locate_zone("America/New_York");
auto anc_zone = locate_zone("America/Anchorage");
// Get the current time in New York and the current time in Anchorage
auto now_utc = system_clock::now();
auto now_nyc = nyc_zone->to_local(now_utc).first;
auto now_anc = anc_zone->to_local(now_utc).first;
// Output the difference
std::cout << make_time(now_nyc - now_anc) << '\n';
}
现在你们都可以很容易理解 – 2012-07-17 11:56:59
使用boost:http://www.boost.org/doc/libs/1_50_0/doc/html/date_time/examples.html#date_time.examples.simple_time_zone – Nim 2012-07-17 12:06:28
准确地说明您的操作系统是什么,或者如果您想使用便携式库(例如提升) – 2012-07-17 13:42:38