Santanu C
Santanu C

Reputation: 1392

Convert timestamp in milliseconds into a timezone in boost

I have a client java library that parses ISO timestamp with timezone using joda-time library and returns a long value (milliseconds since epoch in UTC). I need to develop a server-side framework (in C++) that will use milliseconds since epoch and generate timestamp in any given timezone (e.g. "Europe/Zurich"). I can use local_date_time option like this :

posix_time ptime = epoch(date(1970,1,1)) + ms; //ms sent from client
tz_database tz;
tz.load_from_file(/*path to date_time_zonespec.csv*/);
time_zone_ptr ptr = tz.time_zone_from_region(regionStr); //regionStr = Europe/Zurich
local_date_time mytime(ptime, ptr);

However, I learnt from this post ( C++: Will you choose boost::date_time or icu::date/time library?) that boost::date_time time zone support is broken. A better option is boost::locale. Is there a way to the same steps as above using boost::locale? I was searching for examples online with boost::Locale but could not find any example similar to what I want.

Upvotes: 0

Views: 1026

Answers (1)

Howard Hinnant
Howard Hinnant

Reputation: 218700

Perhaps this free, open-source C++11/14 timezone library could help:

#include "tz.h"
#include <iostream>

date::zoned_time<std::chrono::milliseconds>
convert(date::sys_time<std::chrono::milliseconds> tp)
{
    return date::make_zoned(date::locate_zone("Europe/Zurich"), tp);
}

int
main()
{
    using namespace std::chrono;
    std::cout << convert(date::floor<milliseconds>(system_clock::now())) << '\n';
    std::cout << convert(date::sys_time<milliseconds>{1469137715906ms}) << '\n';
}

This just output for me:

2016-07-21 23:48:35.906 CEST
2016-07-21 23:48:35.906 CEST

It is built on top of the C++11/14 <chrono> library. std::chrono::system_clock measures time since 1970-01-01 UTC. The timezone library helps translate that into localized timezones using the IANA timezone database.

Fully documented, easy to use. High performance. Catches many errors at compile time.

Examples and Recipes.

Upvotes: 2

Related Questions