Convert Boost Ptime To EST UTC-5:00 - c++

I am using the following code to get the current date time (Mountain time)
const boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
//In mountain time I get now = 2013-Apr-08 20:44:22
Now I am using the following method for conversion
ptime FeedConnector::MountaintToEasternConversion(ptime coloTime)
{
return boost::date_time::local_adjustor <ptime, -5, us_dst>::utc_to_local(coloTime);
}
//This function is suppose to give me the time in NewYork (East standard time) and I am getting
2013-Apr-08 16:44:22
Thsi time is wrong any suggestion where I am going wrong ?

As far as I understand wrong time means that it is has one hour difference to expected, i.e. -4 hours instead of expected -5 hours. If yes, then the problem is that the us_std type is pointed as the last parameter of the local_adjustor declaration. If to specify no_dst instead of the use_dst. The code works as expatiated and the difference is -5 hours. The following code demonstrates it (link to online compiled version)
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/local_time_adjustor.hpp>
#include <iostream>
int main(void) {
const boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
const boost::posix_time::ptime adjUSDST = boost::date_time::local_adjustor<boost::posix_time::ptime, -5, boost::posix_time::us_dst>::utc_to_local(now);
const boost::posix_time::ptime adjNODST = boost::date_time::local_adjustor<boost::posix_time::ptime, -5, boost::posix_time::no_dst>::utc_to_local(now);
std::cout << "now: " << now << std::endl;
std::cout << "adjUSDST: " << adjUSDST << std::endl;
std::cout << "adjNODST: " << adjNODST << std::endl;
return 0;
}

Related

Timestamp conversion using cplusplus [duplicate]

How do I get a uint unix timestamp in C++? I've googled a bit and it seems that most methods are looking for more convoluted ways to represent time. Can't I just get it as a uint?
C++20 introduced a guarantee that time_since_epoch is relative to the UNIX epoch, and cppreference.com gives an example that I've distilled to the relevant code, and changed to units of seconds rather than hours:
#include <iostream>
#include <chrono>
int main()
{
const auto p1 = std::chrono::system_clock::now();
std::cout << "seconds since epoch: "
<< std::chrono::duration_cast<std::chrono::seconds>(
p1.time_since_epoch()).count() << '\n';
}
Using C++17 or earlier, time() is the simplest function - seconds since Epoch, which for Linux and UNIX at least would be the UNIX epoch. Linux manpage here.
The cppreference page linked above gives this example:
#include <ctime>
#include <iostream>
int main()
{
std::time_t result = std::time(nullptr);
std::cout << std::asctime(std::localtime(&result))
<< result << " seconds since the Epoch\n";
}
#include<iostream>
#include<ctime>
int main()
{
std::time_t t = std::time(0); // t is an integer type
std::cout << t << " seconds since 01-Jan-1970\n";
return 0;
}
The most common advice is wrong, you can't just rely on time(). That's used for relative timing: ISO C++ doesn't specify that 1970-01-01T00:00Z is time_t(0)
What's worse is that you can't easily figure it out, either. Sure, you can find the calendar date of time_t(0) with gmtime, but what are you going to do if that's 2000-01-01T00:00Z ? How many seconds were there between 1970-01-01T00:00Z and 2000-01-01T00:00Z? It's certainly no multiple of 60, due to leap seconds.
As this is the first result on google and there's no C++20 answer yet, here's how to use std::chrono to do this:
#include <chrono>
//...
using namespace std::chrono;
int64_t timestamp = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
In versions of C++ before 20, system_clock's epoch being Unix epoch is a de-facto convention, but it's not standardized. If you're not on C++20, use at your own risk.
#include <iostream>
#include <sys/time.h>
using namespace std;
int main ()
{
unsigned long int sec= time(NULL);
cout<<sec<<endl;
}
I created a global define with more information:
#include <iostream>
#include <ctime>
#include <iomanip>
#define __FILENAME__ (__builtin_strrchr(__FILE__, '/') ? __builtin_strrchr(__FILE__, '/') + 1 : __FILE__) // only show filename and not it's path (less clutter)
#define INFO std::cout << std::put_time(std::localtime(&time_now), "%y-%m-%d %OH:%OM:%OS") << " [INFO] " << __FILENAME__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") >> "
#define ERROR std::cout << std::put_time(std::localtime(&time_now), "%y-%m-%d %OH:%OM:%OS") << " [ERROR] " << __FILENAME__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") >> "
static std::time_t time_now = std::time(nullptr);
Use it like this:
INFO << "Hello world" << std::endl;
ERROR << "Goodbye world" << std::endl;
Sample output:
16-06-23 21:33:19 [INFO] main.cpp(main:6) >> Hello world
16-06-23 21:33:19 [ERROR] main.cpp(main:7) >> Goodbye world
Put these lines in your header file. I find this very useful for debugging, etc.
Windows uses a different epoch and time units: see
Convert Windows Filetime to second in Unix/Linux
What std::time() returns on Windows is (as yet) unknown to me (;-))

How to get datetime in ISO 8601 format on Windows?

What's a standard way to get a date time in ISO8601 format on Windows using C++? Specifically, I would like it to be formatted as:
2017-02-22T10:00:00.123-05:00
2017-02-22T10:00:00.123 >>> -05:00 <<< # how to print the offset?
I was looking into combining the output of GetLocalTime and GetTimeZoneInformation, but this looks esoteric. There are similar questions on SO, however, I've not found a single one that prints UTC offset in a desired format. Is there a better approach?
The format specifier %z gives you the timezone offset as described in the documentation (e.g. MSDN on strftime) but lefts out the ':'. You can use it like this to get the ':' into your string:
struct tm tmNow;
time_t now = time(NULL); // Get the current time
_localtime64_s(&tmNow, &now);
char bufferTime[26];
char bufferTimezoneOffset[6];
size_t tsizTime = strftime(bufferTime, 26, "%Y-%m-%dT%H:%M:%S", &tmNow); // The current time formatted "2017-02-22T10:00:00"
size_t tsizOffset = strftime(bufferTimezoneOffset, 6, "%z", &tmNow); // The timezone offset -0500
strncpy_s(&bufferTime[tsizTime], 26, bufferTimezoneOffset, 3); // Adds the hour part of the timezone offset
bufferTime[tsizTime + 3] = ':'; // insert ':'
strncpy_s(&bufferTime[tsizTime + 4], 26, &bufferTimezoneOffset[3], 3); // Adds the minutes part of the timezone offset
puts(bufferTime); // Your output: "2017-02-22T10:00:00-05:00"
I left out the milliseconds, as they are not part of the localtime as far as I know.
Maybe something like this. We call GetLocalTime and GetTimeZoneInformation then pass it to the function which returns formatted string.
This is written quickly, not tested besides observing the fact it returns correct result on my machine now. It operates on the fact that SYSTEMTIME has a member Bias where UTC = Localtime + Bias and Bias is set in minutes. So get hours by dividing by 60 and taking absolute value of that. Then we get the minutes in similar way and set the sign depending on if Bias > 0
#include <Windows.h>
#include <string>
#include <sstream>
#include <iomanip>
#include <cmath>
std::string format_system_time(const SYSTEMTIME& sys_time, const TIME_ZONE_INFORMATION& time_zone)
{
std::ostringstream formatted_date_time;
formatted_date_time << std::setfill('0');
formatted_date_time << sys_time.wYear << "-" << std::setw(2) << sys_time.wMonth << "-" <<
std::setw(2) << sys_time.wDay << "T" << std::setw(2) << sys_time.wHour << ":" <<
std::setw(2) << sys_time.wMinute << ":" << std::setw(2) << sys_time.wSecond << "." <<
std::setw(3) << sys_time.wMilliseconds;
//UTC = localtime + bias; bias is in minutes
int utc_offset_hours = time_zone.Bias / 60;
int utc_offset_minutes = std::abs(time_zone.Bias - (utc_offset_hours * 60));
char offset_sign = time_zone.Bias > 0 ? '-' : '+';
formatted_date_time << offset_sign << std::setw(2) << std::abs(utc_offset_hours) << ":" << utc_offset_minutes;
return formatted_date_time.str();
}
int main(int argc, char* argv[])
{
SYSTEMTIME date_and_time;
GetLocalTime(&date_and_time);
TIME_ZONE_INFORMATION time_zone;
GetTimeZoneInformation(&time_zone);
auto& formatted_date_time = format_system_time(date_and_time, time_zone);
return 0;
}
I don't think there is a drop-in solution for c++ on Windows. The closest you can get is InternetTimeFromSystemTime but it is only documented to support RFC1123.
You probably have to code it yourself with GetLocalTime + GetTimeZoneInformation + wsprintf (or GetTimeZoneInformationForYear if you are not dealing with the current time).
Using Howard Hinnant's free, open-source timezone library, which works on VS-2013 and later, but does require some installation:
#include "tz.h"
#include <iostream>
int
main()
{
using namespace std;
using namespace std::chrono;
using namespace date;
auto zt = make_zoned(current_zone(), floor<milliseconds>(system_clock::now()));
cout << format("%FT%T%Ez\n", zt);
}
This just output for me:
2017-02-22T17:29:03.859-05:00

Get time difference with DST considered

I am using Boost.Date_time to get the time difference between two dates. I want the code to consider DST change as well during these days and give me the correct interval.
Consider this example. On 1-Nov-2015, the DST is going to change in USA. At 2:00 hours, the clock will be moved back to 1:00. The output of the below code doesn't reflect that. It gives 23 hours as the difference.
date d1(2015, 11, 1);
ptime nov1_00(d1, hours(0));
ptime nov1_23(d1, hours(23));
seconds = (nov1_23 - nov1_00).total_seconds();
Output:
2015-Nov-01 00:00:00. 2015-Nov-01 23:00:00. Seconds: 82800
Is there a way in boost to specify the DST requirement in this scenario?
You should be using local times:
Live On Coliru
#include <boost/date_time/local_time/local_time.hpp>
#include <boost/date_time/local_time/local_date_time.hpp>
#include <boost/date_time/local_time/local_time_io.hpp>
#include <boost/make_shared.hpp>
#include <iostream>
int main() {
namespace lt = boost::local_time;
namespace pt = boost::posix_time;
using date = boost::gregorian::date;
lt::tz_database db;
db.load_from_file("/home/sehe/custom/boost/libs/date_time/data/date_time_zonespec.csv");
//for (auto region : db.region_list()) std::cout << region << "\n";
auto NY = db.time_zone_from_region("America/New_York");
date const d1(2015, 11, 1);
lt::local_date_time nov1_00(d1, pt::hours(0), NY, true);
lt::local_date_time nov1_23(d1, pt::hours(23), NY, false);
lt::local_time_period period(nov1_00, nov1_23);
std::cout << "period: " << period << "\n";
std::cout << "duration: " << period.length() << "\n";
// if you insist:
auto seconds = (nov1_23 - nov1_00).total_seconds();
std::cout << "seconds: " << seconds << "\n";
}
Prints:
period: [2015-Nov-01 00:00:00 EDT/2015-Nov-01 22:59:59.999999 EST]
duration: 24:00:00
seconds: 86400

Unexpect result from boost posix_time

When I run this in my ubuntu, I get the bottom result. What could go wrong with this? There is no way the result year is 1970, and see when I do the reconvert the ms back, the result aren't the same. But when I run it at http://coliru.stacked-crooked.com/ it was fine.
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <string>
#include <iostream>
int main()
{
using namespace boost::posix_time;
ptime time_t_epoch(boost::gregorian::date(1970,1,1));
auto ms = (boost::posix_time::microsec_clock::local_time() - time_t_epoch).total_microseconds();
std::cout << "ms: " << ms << std::endl;
std::cout << "ms: " << boost::posix_time::microseconds(ms).total_microseconds() << std::endl;
ptime newTime = time_t_epoch + boost::posix_time::microseconds(ms);
std::cout << boost::posix_time::to_iso_string(time_t_epoch) << std::endl;
std::cout << boost::posix_time::to_iso_string(newTime) << std::endl;
std::stringstream ss;
ss << newTime;
std::cout << ss.str()<< std::endl;
}
Result:
ms: 1424976249761218
ms: 4576956085582
19700101T000000
19700222T232236.085582
1970-Feb-22 23:22:36.085582
Machine environment = Ubuntu 12 + cmake 2.8.7 + boost 1.48.0.2
1970/01/01 + 4576956085582 microseconds -> 1970-Feb-22 is correct
1970/01/01 + 1424976249761218 microseconds -> 2015-Feb-26 so ms is presumably correct
What is not correct is that
boost::posix_time::microseconds(ms).total_microseconds() != ms
It might be related to this bug https://svn.boost.org/trac/boost/ticket/3487 though I'm not sure.

Invalid null pointer error when converting std::chrono::system_clock::time_point::min() to string

I am following an example in Nicolai M. Josuttis' "The C++ Standard Library (Second Edition)", page 152-153, which details an example to print the epoch, current time, minimum and maximum times of the std::chrono::system_clock introduced in C++11.
I am using Microsoft Visual Studio 2012, and get an assertion triggered in <xstring>, due to an invalid null pointer. This occurs on the line std::string ts = std::ctime( &t ) in the code below after setting tp = std::chrono::system_clock::time_point::min();
#include <chrono>
#include <ctime>
#include <string>
#include <iostream>
std::string asString( const std::chrono::system_clock::time_point& tp )
{
std::time_t t = std::chrono::system_clock::to_time_t( tp );
std::string ts = std::ctime( &t );
ts.resize( ts.size()-1 );
return ts;
}
int main()
{
std::chrono::system_clock::time_point tp;
std::cout << "epoch: " << asString(tp) << std::endl;
tp = std::chrono::system_clock::now();
std::cout << "now: " << asString(tp) << std::endl;
tp = std::chrono::system_clock::time_point::min();
std::cout << "min: " << asString(tp) << std::endl;
tp = std::chrono::system_clock::time_point::max();
std::cout << "max: " << asString(tp) << std::endl;
return 0;
}
Is this due to an implementation error by Dinkumware in the <chrono> library, or just a typo/mistake in the book? I have gone over the code given in the book again and again to see if I have copied it out incorrectly, but this does not appear to be the case. I'd be very grateful for any insights given.
It looks like std::ctime returns NULL, which indicates an incorrect t value. Probably because the call to asString uses a value of time_point that cannot be represented in time_t type.