Boost date add one day, non standard GMT string - c++

In C++ what is the simplest way to add one day to a date in this format:
"20090629-05:57:43"
Probably using Boost 1.36 - Boost::date, Boost::posix_date or any other boost or std library functionality, I'm not interested in other libraries.
So far I came up with:
format the string (split date and time parts as string op) to be able to initialize boost::gregorian::date, date expects format like:
"2009-06-29 05:57:43"
I have
"20090629-05:57:43"
add one day (boost date_duration stuff)
convert back to_simple_string and append the time part (string operation)
Is there any easier/niftier way to do this?
I am looking at run time efficiency.
Example code for the above steps:
using namespace boost::gregorian;
string orig("20090629-05:57:43");
string dday(orig.substr(0,8));
string dtime(orig.substr(8));
date d(from_undelimited_string(dday));
date_duration dd(1);
d += dd;
string result(to_iso_string(d) + dtime);
result:
20090630-05:57:43

That's pretty close to the simplest method I know of. About the only way to simplify it further would be using facets for the I/O stuff, to eliminate the need for string manipulation:
#include <iostream>
#include <sstream>
#include <locale>
#include <boost/date_time.hpp>
using namespace boost::local_time;
int main() {
std::stringstream ss;
local_time_facet* output_facet = new local_time_facet();
local_time_input_facet* input_facet = new local_time_input_facet();
ss.imbue(std::locale(std::locale::classic(), output_facet));
ss.imbue(std::locale(ss.getloc(), input_facet));
local_date_time ldt(not_a_date_time);
input_facet->format("%Y%m%d-%H:%M:%S");
ss.str("20090629-05:57:43");
ss >> ldt;
output_facet->format("%Y%m%d-%H:%M:%S");
ss.str(std::string());
ss << ldt;
std::cout << ss.str() << std::endl;
}
That's longer, and arguably harder to understand, though. I haven't tried to prove it, but I suspect it would be about equal runtime-efficiency that way.

Related

How to deal with time in C++

I have a question about managing the date and time in c++. I have two classes Plane and Flight in my program.
My Plane will consist data as:
string tailNumber;//Plane's unique trait
vector<vector<string>> planeSchedule;//2D string vector to contain plane's depature date and arrival date
My Flight class will consist data as:
string tailNumber;//Plane's unique trait
string departureDate;
string arrivalDate;
In my main class, I will input the value for departureDate and arrivalDate in format: "YYYY/MM/DD HH:MM" such as: "2019/04/15 10:30" and "2019/04/16 9:30" (I will use the 24-hour format and time will be GMT).
My question is how do I convert the two strings above to a proper format to store in my planeSchedule, so that I will be able to avoid the time conflict in the planeSchedule.
For example, If the next time I'm adding a flight with departure and arrival date beetween the: 2019/04/15 10:30" and "2019/04/16 9:30" such as: "2019/04/15 13:30" and "2019/04/16 7:30", I will get an error like "Flight conflict, plane is not available to flight."
My professor recommends using an unsigned long int to store time, but I really do not know where to start to solve this problem. Any help/suggestion is appreciated.
The go-to place regarding dates and times in C++ is <chrono>. Some of it has been with us since C++11, some of it we'll see coming with C++20. It works in conjunction with the C-style date and time utilities in <ctime>, which might even suffice for your purposes.
Trying to handle date / time as either integers or strings, parsing them from input, comparing, and converting them to strings for output, will effectively result in you reimplementing parts of what's already in those headers (a.k.a. "reinventing the wheel").
I have two pieces of advice based on long experience with systems that did it badly :-)
The first is to not store date and time information as strings or integral values, especially when C++ has very good support for that in std::chrono. If you use the correct types, comparisons and manipulations become relatively simple.
Second, make sure you use UTC for all times. You should convert local times to UTC as soon as possible after getting them, and convert back to local as late as possible when presenting them. This will also greatly simplify comparisons.
By way of example, here's a complete program which show the simplicity(a) in action:
#include <iostream>
#include <iomanip>
#include <sstream>
#include <chrono>
using std::chrono::system_clock;
using std::chrono::duration_cast;
namespace {
system_clock::time_point getTimePoint(std::string strTime) {
std::tm myTm = {};
std::stringstream ss(strTime.c_str());
ss >> std::get_time(&myTm, "%Y/%m/%d %H:%M");
return system_clock::from_time_t(std::mktime(&myTm));
}
void outputTime(const char *desc, system_clock::time_point &tp) {
std::time_t now = system_clock::to_time_t(tp);
std::cout << desc
<< std::put_time(std::localtime(&now), "%Y-%m-%d %H:%M") << "\n";
}
}
int main() {
std::string startTime = "2019/04/15 10:30";
std::string endTime = "2019/04/16 09:30";
auto startTp = getTimePoint(startTime);
auto endTp = getTimePoint(endTime);
outputTime("Start time: ", startTp);
outputTime(" End time: ", endTp);
auto duration = duration_cast<std::chrono::minutes>(endTp - startTp);
std::cout << "\nThere are " << duration.count() << " minutes between "
<< startTime << " and " << endTime << "\n";
}
The output of that program is:
Start time: 2019-04-15 10:30
End time: 2019-04-16 09:30
There are 1380 minutes between 2019/04/15 10:30 and 2019/04/16 09:30
(a) Yes, the program may seem reasonably big but that's just because of the stuff making it a complete program. The getTimePoint and outputTime functions show how to do the conversion to and from time points, and the meat of the simplicity is the line containing duration_cast to get the number of minutes between the two time points.

How do I write a message timestamp to a log file?

I'm trying to create a logging file for my C++ program. My goal is to put two timestamps at two points of my program and print in a file the CPU time period between these two points. I'm doing this because I want to know which parts of my code are the most time consuming so I can make improvements (so there may be several chunks of code I want to measure). So far, I've made a function that, when called, prints a string that I pass as an argument, to a file:
#define LOGFILE "myprog.log"
void Log (std::string message){
std::ofstream ofs;
ofs.open(LOGFILE, std::ofstream::out | std::ios::app);
ofs << message << std::endl;
ofs.close();
}
However, I'm having difficulty figuring out how to print the CPU timestamp. Firstly, I don't know what time measurement format I should use (should I use the chrono or the time_t types?) I'm trying to print a time period so it would be helpful if there was a type for duration (I've tried chrono::duration but it seems to require C++11 support). Secondly, given I know what type to use, how do I print it to the file? Is there a way to cast that type to a string? Or can I pass it directly to my function and print it somehow?
This has troubled me a lot the last couple of days and I can't seem to figure it out, so any input would be really helpful. Thanks in advance!
Get a CPU Timestamp
You'll want to use std::chrono::system_clock to get this timestamp. Do not use std::chrono::steady_clock or std::chrono::high_resolution_clock, as those are for making high-precision timing measurements, and do not guarantee fidelity or accuracy to wall-clock time.
auto now = std::chrono::system_clock::now();
//now is a time_point object describing the instant it was recorded according to your system clock
Print this CPU Timestamp in a readable format
In C++20, this is pretty trivial.
std::string formatted_time = std::format("{0:%F_%T}", now);
ofs << formatted_time << ": " << message << std::endl;
%F is a substitute for %Y-%m-%D, which will output year-month-day in ISO format, i.e. 2018-10-09.
%T is the same for %H:%M:%S, which will output a time, i.e. 17:55:34.786
See the specification for std::format and std::formatter for more information about how to specify these parameters.
As of December 2020, no major compilers support the <format> library, yet, so as an alternative you can use fmt, which is a standalone implementation of the library.
Prior to C++20
Consider Howard Hinnant's date library, most of which is being incorporated into C++20 as a new part of the chrono library. The format function found in that library uses the same syntax as suggested above for the C++20 version, although without integration with std::format.
I'm usually use my implementation for such things.
#include <chrono>
#include <ctime>
// strftime format
#define LOGGER_PRETTY_TIME_FORMAT "%Y-%m-%d %H:%M:%S"
// printf format
#define LOGGER_PRETTY_MS_FORMAT ".%03d"
// convert current time to milliseconds since unix epoch
template <typename T>
static int to_ms(const std::chrono::time_point<T>& tp)
{
using namespace std::chrono;
auto dur = tp.time_since_epoch();
return static_cast<int>(duration_cast<milliseconds>(dur).count());
}
// format it in two parts: main part with date and time and part with milliseconds
static std::string pretty_time()
{
auto tp = std::chrono::system_clock::now();
std::time_t current_time = std::chrono::system_clock::to_time_t(tp);
// this function use static global pointer. so it is not thread safe solution
std::tm* time_info = std::localtime(&current_time);
char buffer[128];
int string_size = strftime(
buffer, sizeof(buffer),
LOGGER_PRETTY_TIME_FORMAT,
time_info
);
int ms = to_ms(tp) % 1000;
string_size += std::snprintf(
buffer + string_size, sizeof(buffer) - string_size,
LOGGER_PRETTY_MS_FORMAT, ms
);
return std::string(buffer, buffer + string_size);
}
It returns current time in format: 2018-09-23 21:58:52.642.
Yes it requires --std=c++11 or above.
For the record:
If C++20 features are not available, as in my case, you can use the following:
#include <ctime>
#include <iomanip>
#include <iostream>
using namespace std ;
time_t now = time(nullptr) ;
cout << put_time(localtime(&now), "%T") << endl ;
put_time is defined in iomanip library, look at https://en.cppreference.com/w/cpp/io/manip/put_time, and time_t and localtime are from the ctime, https://en.cppreference.com/w/cpp/chrono/c/ctime
If you want a more manual approach, this is what I've used before
char buffer[MAX_BUFFER_SIZE];
time_t t = time(NULL);
struct tm *lt = localtime(&t);
snprintf(buffer, MAX_BUFFER_SIZE, "%02d/%02d/%02d %02d:%02d:%02d", lt->tm_mon+1, lt->tm_mday, lt->tm_year%100, lt->tm_hour, lt->tm_min, lt->tm_sec);
Then just output buffer, which now contains string representation of time, to your file.

How to insert a colon in between string as like date formats in c++?

I have string 20150410 121416 in c++.
I need to turn this into 20150410 12:14:16
How can i insert a colon to the string?
One can format date/times in C and C++ with strftime. There also exists a non-standard but common POSIX function called strptime one can use to parse times. One could use these to parse your date/time in your input format, and then format it back out in your desired format.
That is, assuming you didn't want to write the parsing code yourself.
If you have C++11, then you could use this free, open-source date/time library to help you do all this with strftime-like format strings. Such code could look like:
#include "tz.h"
#include <iostream>
#include <sstream>
int
main()
{
using namespace date;
std::string input = "20150410 121416";
std::stringstream stream{input};
stream.exceptions(std::ios::failbit);
sys_seconds tp;
parse(stream, "%Y%m%d %H%M%S", tp);
auto output = format("%Y%m%d %T", tp);
std::cout << output << '\n';
}
Output:
20150410 12:14:16
One advantage of using a date/time parsing/formatting library, as opposed to just treating these as generic strings, is that you can more easily alter the formatting, or manipulate the datetime during the format conversion (e.g. have it change timezones).
For example, next month the specification might change on you and now you're told that this is a timestamp representing local time in Moscow and you need to convert it to local time in London and output it in the form YYYY-MM-DD HH:MM:SS <UTC offset>. The above code hardly changes at all if you're using a good date/time library.
#include "tz.h"
#include <iostream>
#include <sstream>
int
main()
{
using namespace date;
std::string input = "20150410 121416";
std::stringstream stream{input};
stream.exceptions(std::ios::failbit);
local_seconds tp;
parse(stream, "%Y%m%d %H%M%S", tp);
auto moscow_time = make_zoned("Europe/Moscow", tp);
auto london_time = make_zoned("Europe/London", moscow_time);
auto output = format("%F %T %z", london_time);
std::cout << output << '\n';
}
2015-04-10 10:14:16 +0100
But if you started out just doing string manipulation, all of the sudden you've got a major task in front of you. Writing code that understands the semantics of the datetime "20150410 121416" is a significant leap above manipulating the characters of "20150410 121416" as a string.
<script type="text/javascript">
function formatTime(objFormField){
intFieldLength = objFormField.value.length;
if(intFieldLength==2 || intFieldLength == 2){
objFormField.value = objFormField.value + ":";
return false;
}
}
</script>
Enter time <input type="text" maxlength="5" minlength="5" onKeyPress="formatTime(this)"/>

boost: time_facet milliseconds without dot

I need to create a timestamp with boost in the format:
YYYYmmDDhhMMssFFFF (with F = Milliseconds).
I use
facet->format("%Y%m%d%H%M%S%F");
but the output includes always a dot between seconds and milliseconds. This is the output:
"20150202140830.779716"
Is there a better way to achieve my format than to replace the dot and cut the last two digits by hand?
In case you're interested, I implemented a custom facet the other day here: Format a posix time with just 3 digits in fractional seconds
You could use the same approach here:
Live On Coliru
#include "time_facet.hpp"
#include <boost/date_time/posix_time/posix_time.hpp>
int main()
{
using namespace boost::posix_time;
ptime const date_time = microsec_clock::local_time();
std::cout << date_time << std::endl;
auto facet = new time_facet("%Y-%b-%d %H:%M:%S%4 %z");
std::cout.imbue(std::locale(std::cout.getloc(), facet));
std::cout << date_time << std::endl;
}
Prints:
2015-Feb-02 22:01:00.926982
2015-Feb-02 22:01:009269

c++ to_string error with date

I am trying to write a function that returns the date as a string. I went about this like so:
string date() // includes not listed for sake of space, using namespace std
{
tm timeStruct;
int currentMonth = timeStruct.tm_mon + 1;
int currentDay = timeStruct.tm_mday;
int currentYear = timeStruct.tm_year - 100;
string currentDate = to_string(currentMonth) + "/" + to_string(currentDay) + "/" + to_string(currentYear);
return currentDate;
}
this is giving four compile time errors.
1 of these:
to_string was not declared in this scope
and 3 of these:
Function to_string could not be resolved
one for each use of to_string.
According to everywhere else on the internet, this code should work. Can someone please shed some light on the subject?
As has been mentioned in the comments, what you're trying to use requires C++11. This means both a compiler that supports C++11 (E.g. GCC 4.7+), AND possibly manually enabling C++11 (E.g. flag -std=c++11), so check both of those if you believe it should be working for you.
If you're stuck with a compiler that does not support C++11, you can use the following to achieve what you want, with regular C++:
string date()
{
tm timeStruct;
int currentMonth = timeStruct.tm_mon + 1;
int currentDay = timeStruct.tm_mday;
int currentYear = timeStruct.tm_year - 100;
char currentDate[30];
sprintf(currentDate, "%02d/%02d/%d", currentMonth, currentDay, currentYear);
return currentDate; // it will automatically be converted to string
}
Note that for the Day and Month parameters, I used %02d to force it to display at least 2 digits, so 5/1 will actually be represented as 05/01. If you don't want that, you can just use %d instead, which will behave like your original to_string. (I'm not sure what format you're using for currentYear, but you'll probably also want to use either %02d or %04d for that parameter)
std::to_string is part of C++11 and is in the <string> header. The following code works with g++ 4.7, as well as recent versions of clang and VC++. If compiling a file with these contents does not work for you, you are either invoking the compiler incorrectly for C++11 or using a compiler version with insufficient support for C++11.
#include <string>
int main() {
int i;
auto s = std::to_string(i);
}
However there is a better way to print dates in C++11. Here's a program that prints the current date (in ISO 8601 format).
#include <ctime> // time, time_t, tm, localtime
#include <iomanip> // put_time
#include <iostream> // cout
#include <sstream> // stringstream
#include <stdexcept> // runtime_error
#include <string> // string
std::string date() {
static constexpr char const *date_format = "%Y-%m-%d"; // ISO 8601 format
auto t = std::time(nullptr);
if (static_cast<std::time_t>(-1) == t) {
throw std::runtime_error{"std::time failed"};
}
auto *cal = std::localtime(&t);
if (nullptr == cal) {
throw std::runtime_error{"std::localetime failed"};
}
std::stringstream ss;
ss << std::put_time(cal, date_format);
return ss.str();
}
int main() { std::cout << date() << '\n'; }
Unfortunately gcc 4.8 appears to lack put_time (and of course VC++ currently lacks constexpr and universal initializers, but that is easily worked around. VC++ has put_time).