Created
June 30, 2014 19:41
-
-
Save makomweb/0a2c2ae8e3ba87ab85b7 to your computer and use it in GitHub Desktop.
boost date time UTC versus local time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include "boost/date_time/local_time/local_time.hpp" | |
#include "boost/date_time/c_local_time_adjustor.hpp" | |
boost::posix_time::time_duration get_utc_offset(const boost::posix_time::ptime& time_stamp) | |
{ | |
using boost::posix_time::ptime; | |
const ptime local_time = boost::date_time::c_local_adjustor<ptime>::utc_to_local(time_stamp); | |
return local_time - time_stamp; | |
} | |
std::wstring get_utc_offset_string(const boost::posix_time::ptime& utc_time_stamp) | |
{ | |
const boost::posix_time::time_duration td = get_utc_offset(utc_time_stamp); | |
const wchar_t fillChar = L'0'; | |
const wchar_t timeSeparator = L':'; | |
std::wostringstream out; | |
out << (td.is_negative() ? L'-' : L'+'); | |
out << std::setw(2) << std::setfill(fillChar) | |
<< boost::date_time::absolute_value(td.hours()); | |
out << L':'; | |
out << std::setw(2) << std::setfill(fillChar) | |
<< boost::date_time::absolute_value(td.minutes()); | |
return out.str(); | |
} | |
int main () | |
{ | |
using namespace std; | |
using namespace boost::posix_time; | |
typedef boost::local_time::local_date_time time_t; | |
typedef boost::local_time::time_zone_ptr time_zone_t; | |
time_t now(second_clock::local_time(), time_zone_t()); | |
std::cout << "Now is " << now.local_time() << std::endl; | |
const ptime utc_now = second_clock::universal_time(); | |
const wstring offset = get_utc_offset_string(utc_now); | |
wcout << "UTC offset is " << offset.c_str() << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment