私はグレッグの良い答えを数日間見つめてきましたが、タイムゾーンライブラリに構文シュガーを追加することを考えています:
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
れ、それを介してストリーミングして、あるタイムゾーンから別のタイムゾーンに変換できるようになります。これは非常に単純なデバイスであり、タイムゾーン ライブラリからいくつかの情報を削除することを犠牲にして、構文シュガーを追加するだけです。
次のように使用されます。
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';
}