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.
Related
I am attempting to use Howard Hinnant's date library (https://github.com/HowardHinnant/date) to read user input into a datetime object. I would like to use this library since it's modern, and is to be included in C++20.
The program should be able to accept datetimes in ISO 8601 format (YYYY-MM-DDTHH:MM:SS+HHMM etc, eg 2020-07-07T18:30+0100) as well as simple datetimes in the form DD-MM HH:MM or HH:MM. In the second case, it should assume that the missing information is to be filled in with the current date/year (the timezone is to be dealt with later).
Here is my attempt at doing this.
using namespace date;
int main(int argc, char ** argv)
{
std::istringstream ss { argv[1] };
std::chrono::system_clock::time_point dt
{ std::chrono::system_clock::now() };
if ( date::from_stream(ss, "%F T %T %z", dt) ) {
std::cout << "Cond 1 entered\n";
}
else if ( ss.clear(), ss.seekg(0); date::from_stream(ss, "%d-%m %R", dt)) {
std::cout << "Cond 2 entered\n";
}
std::cout << dt << "\n";
}
For the first format, this works as expected:
./a.out 2020-06-07T18:30:00+0200
Cond 1 entered
2020-06-07 16:30:00.000000000
However, the second method returns something strange, depending on the compiler used. When compiled with GCC and -std=c++17/-std=c++2a:
./a.out "07-08 15:00"
Cond 2 entered
1754-04-06 13:43:41.128654848
EDIT 2: When compiled with LLVM and -std=c++2a:
./a.out "07-08 15:00"
Cond 2 entered
0000-08-07 15:00:00.000000
which is a little closer to what I was expecting.
I'd rather not have the behaviour dependent on the compiler used though!
I'm really stumped as to what's going on here, and I can't seem to make head or tail of the documentation.
How can I get date::from_stream to simply overwrite the time and date and leave everything else?
EDIT 1:
For clarity, I was (incorrectly) expecting that when the second condition is entered the current year is preserved, since the time_point object was initialised with the current year. E.g I hoped the second call to from_stream would leave the time_point object as 2020-08-07 15:00:33.803726000 in my second example.
See comments for further info.
EDIT 2:
Added results of trying with different compilers.
Good question!!!
You're not doing it quite right, and you found a bug in date.h! :-)
First, I've fixed the bug you hit here. The problem was that I had the wrong value for not_a_year in from_stream, and that bug has been hiding in there for years! Thanks much for helping me find it! To update just pull the tip of the master branch.
When your program is run with the fixed date.h with the argument "07-08 15:00", it enters neither condition and prints out the current time.
Explanation:
The semantics of from_stream(stream, fmt, x) is that if stream doesn't contain enough information to fully specify x using fmt, then stream.failbit gets set and x is not modified. And "07-08 15:00" doesn't fully specify a system_clock::time_point.
The bug in date.h was that date.h was failing to recognize that there wasn't enough information to fully specify the system_clock::time_point, and was writing deterministic garbage to it. And that garbage happened to produce two different values on LLVM/libc++ and gcc because of the different precisions of system_clock::time_point (microseconds vs nanoseconds).
With the bug fix, the parse fails outright, and thus doesn't write the garbage.
I'm sure your next question will be:
How do I make the second parse work?
int main(int argc, char ** argv)
{
std::istringstream ss { argv[1] };
auto dt = std::chrono::system_clock::now();
ss >> date::parse("%FT%T%z", dt);
if (!ss.fail())
{
std::cout << "Cond 1 entered\n";
}
else
{
ss.clear();
ss.seekg(0);
date::month_day md;
std::chrono::minutes hm;
ss >> date::parse("%d-%m", md) >> date::parse(" %R", hm);
if (!ss.fail())
{
std::cout << "Cond 2 entered\n";
using namespace date;
auto y = year_month_day{floor<days>(dt)}.year();
dt = sys_days{y/md} + hm;
}
}
std::cout << dt << "\n";
}
The first parse is just as you had it, except that I switched the use of parse for from_stream which is a little higher level API. This doesn't really matter for the first parse, but makes the second parse neater.
For the second parse you need to parse two items:
A month_day
A time of day
And then combine those two elements with the current year to produce the desired time_point.
Now each parse fully specifies the variable it is parsing from the stream.
The mistake you made originally was in imagining that there is a "year field" under the hood of system_clock::time_point. And actually this data structure is nothing but a count of microseconds or nanoseconds (or whatever) since 1970-01-01 00:00:00 UTC. So the second parse has to:
Parse the fields, and then
Deconstruct the time_point into fields to get the current year, and then
Put the fields back together again into a time_point.
I need to serialize a UTC date time instance from java to c++ using the minimal length of pure ByteBuffer of unsigned chars.
I need the time point with to be able to support minimum nanoseconds precision.
From the java side i have looked in the classes ZonedDateTime and OffsetDateTime and seen what kind of primitive they are using to store the time and all together this is equal to 17 bytes which is kind of a lot.
Please note that i am here not transferring the zone itself since i have not found a way to map those zone strings from IANA to integers. Thus i guess the zone offset will be enough. Since bought sides will have to convert their time point to a particular offset before sending it to the server lets say that will be UTC 0. I am looking for a solution that is queering the local time i.e. no NTP servers involved!
the java side looks like this:
// 4 byte
Integer year = offsetDateTime.getYear();
// 1 byte
Integer month = offsetDateTime.getMonthValue();
// 1 byte
Integer day = offsetDateTime.getDayOfMonth();
// 1 byte
Integer hour = offsetDateTime.getHour();
// 1 byte
Integer minutes = offsetDateTime.getMinute();
// 1 byte
Integer seconds = offsetDateTime.getSecond();
// 4 byte
Integer nanoSeconds = offsetDateTime.getNano();
// 4 byte
Integer utcZoneTimeTotalSecondsOffset = offsetDateTime.getOffset().getTotalSeconds();
on the c++ side i need to do the same as well as to be able to construct a time point from all those integers above.
I have found how to get the the above information except the utcOffset i.e. the last integer.
i would like to use chrono to consume this buffer and instantiate a time point from it. however i am not able to find a way to to get the time offset in c++. How do i get the time offset with chrono and then construct a time point from the above information?
auto now = std::chrono::system_clock::now();
time_t itt = std::chrono::system_clock::to_time_t(now);
tm utc_tm = *gmtime(&itt);
std::cout << utc_tm.tm_year + 1900 << '-';
std::cout << utc_tm.tm_mon + 1 << '-';
std::cout << utc_tm.tm_mday << ' ';
std::cout << utc_tm.tm_hour << ':';
std::cout << utc_tm.tm_min << ':';
std::cout << utc_tm.tm_sec << '\n';
? wher is the time zoneOffset here ?
if i use
utc_tm.tm_gmtoff
this is giving me the wrong information . at least in my case. So i believe gmtoff is not the way to go , but if gmtoff is not the way then what is?
Not a complete answer, but here is one way one might serialize a C++ local time point using Howard Hinnant's free, open source time zone library.
#include "date/tz.h"
#include <iostream>
#include <sstream>
std::string
to_string(date::zoned_time<std::chrono::nanoseconds> t)
{
using namespace std;
using namespace date;
ostringstream out;
out << t.get_sys_time().time_since_epoch().count()
<< ' ' << t.get_time_zone()->name();
return out.str();
}
date::zoned_time<std::chrono::nanoseconds>
from_string(const std::string& s)
{
using namespace std;
using namespace std::chrono;
using namespace date;
istringstream in{s};
long long ns;
std::string tz_name;
in >> ns >> tz_name;
return {tz_name, sys_time<nanoseconds>{nanoseconds{ns}}};
}
int
main()
{
using namespace std;
using namespace std::chrono;
using namespace date;
zoned_time<nanoseconds> zt{current_zone(), system_clock::now()};
cout << zt << '\n';
auto s = to_string(zt);
cout << s << '\n';
zt = from_string(s);
cout << zt << '\n';
}
I'm using a std::string to represent the serialization, which one might send across a network.
This example begins in main with creating a nanosecond-precision local time point, stored in date::zoned_time<nanoseconds>, using the computer's current local time zone, and the current UTC time. main first simply prints this time stamp out, which for me just output:
2019-09-11 12:37:04.846272000 EDT
which is my current local date/time and time zone abbreviation.
Next the program converts this to a string with a small (but not necessarily minimal) number of ASCII characters to completely describe the local time point. I've chosen the format:
<Number of nanoseconds since epoch> <IANA time zone name>
In this example, that string is:
1568219824846272000 America/New_York
This string is formed in to_string, which simply streams out the "time since epoch" of the system time, of the zoned_time. Then adds a space, and streams out the name of the time zone.
from_string reverses this operation by reading in the number of nanoseconds, and then reading in the time zone name. It then forms a zoned_time<nanoseconds> by pairing the time zone name, and forming a sys_time<nanoseconds> with the integer that was parsed.
main prints out the parsed zoned_time to ensure we have a loss-less round trip:
2019-09-11 12:37:04.846272000 EDT
In order to get a loss-less conversion that includes local time, one really needs to transmit the IANA time zone name, not just the current UTC offset. With only the UTC offset, one can recover the exact UTC time point. But one can not perform any local time arithmetic, or comparison with other local time points because one can not know the rules for when one changes the UTC offset. Only with the full IANA time zone name can one pass the information along about those rules.
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(¤t_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.
I am currently trying to create a header file that takes information from a user and displays information in a form.
For the most part, I have had no problem, however, I need the user to input their date of birth in the format MMDDYYYY, and then convert it to MM/DD/YYYY and display it in the form.
My problem is that if the user inputs the month '01-09', what displayed was nowhere near correct. I still need to display the month the exact way the user input it, so it has to be displayed as (i.e. 01/01/1967).
The variable for the patient's date of birth is called int patientDateOfBirth.
This data type cannot be changed, it has to be an int.
The method in the header file that I am using is as follows:
void PatientDemographicInformation::printPatientDateOfBirth( )
{
int userMonth, userDay, userYear;
String birthDate = String(itoa(patientDateOfBirth));
// Calculation to determine month, day, and year from the MMDDYYYY format.
userMonth = scanf ("%d", &userMonth);
// this was another method I used, however the leading zero messed it up.
// userMonth = patientDateOfBirth / 1000000;
userDay = patientDateOfBirth / 10000 % 100;
userYear = patientDateOfBirth % 10000;
cout << userMonth << "/";
cout << setfill('0') << setw(2) << userDay << "/";
cout << userYear;
}
Also, this is the first time I am using this forum, so if my formatting is off, please forgive me. I also have little experience with this language, so if the answer is simple, please go easy on me!
Thank you.
EDIT: I've just noticed that there is the variable String birthDate that is not used in the calculation. I was not sure if converting the int into a String would work, but I gave it a shot regardless, but it did not work and I forgot to remove that variable. If that could work, however, please let me know.
EDIT: Sorry if I wasn't as clear as I had hoped to be. I want the user to input a date of birth in the format MMDDYYYY and output it as MM/DD/YYYY, meaning I have to separate the month, day, and year into seperate variables and then put them into a cout statement.
The problem that I am having is if the user puts a 01 thru 09 as the month (i.e. 01141967),
When the method tries to do the calculation, I get some strange number in the output (i.e. 112230056/00004814/5599932) or the like. I am completely stumped by this dilemma. I've searched forever trying to find some kind of answer and I have tried several methods, all not working.
The impression you gave is that you have a patientDateOfBirth integer, in one the following formats: mmddyyyy OR mddyyyy, is that correct? If it is, the original
int month = patientDateOfBirth / 1000000;
int day = patientDateOfBirth / 10000 % 100;
int year = patientDateOfBirth % 10000;
should work ok, regardless of leading zeroes on some original input. An alternative would be using C++11's <chrono> classes or Boost's <boost/date_time.hpp> for your conversions...
In the Boost date time library, is there a utility function for converting month short strings (e.g. Jan, Feb, Mar, Apr) to boost::gregorian::greg_month type? The documentation for the library isn't great and I can't see anything in the headers.
A hacky work around could be:
#include <iostream>
#include <boost/date_time/gregorian/gregorian.hpp>
int main(void)
{
auto ptr = boost::gregorian::greg_month::get_month_map_ptr();
if (ptr)
{
auto it = ptr->begin();
for(; it != ptr->end(); ++it)
{
std::cout << it->first << " " << it->second << '\n';
}
}
}
This map contains mapping between all the short/long names and the short necessary to create a greg_month instance. Just need to create a little wrapper around it...
per Graeme's discovery, there is a convenience function which wraps this already boost::date_time::month_str_to_ushort<>
Yes, there are boost date time facets that can be used to create locales and put into streams.
Beware though that if you are going to print or parse a large number of dates and times you do not create the facet and locale for each one you parse.
Look here for documentation on inputting dates. Some of their examples use short month names, which appears to have %b as its format specifier