0

I have a task to make a function, which will convert time objects (QString type) to std::chrono::milliseconds. The format, which should be processed is

QString("HH:MM:SS DD-MM-YYYY") to std::chrono::milliseconds

I searched for answers before here Stack Overflow, and in other sources in google. In result, I have written this code, and its correct, but I am totally confused how it works. The questions are:

  • Why do I have to subtract chronoUserTime - chronoEpochTime instead of using chronoUserTime ?
  • Are there any ways, to perfome this in direct way, like in Qt style addDays, setTime, etc ?

const std::chrono::milliseconds &xml_order_base::converter(QString dateTime)
{
   char *dateChar = const_cast<char*>(dateTime.toStdString().c_str());
   std::tm ct;
   strptime(dateChar, "%Y-%m-%d %H:%M:%S", &ct);
   auto chronoUserTime = std::chrono::system_clock::from_time_t(std::mktime(&ct));

   std::tm et;
   strptime("1970-01-01 00:00:00", "%Y-%m-%d %H:%M:%S", &et); //strptime("Thu Jan 1 1970 00:00:00", 
   "%a %b %d %Y %H:%M:%S", &et);
   auto chronoEpochTime = std::chrono::system_clock::from_time_t(std::mktime(&et));

   auto resultInMS = std::chrono::duration_cast<std::chrono::milliseconds>(chronoUserTime - 
   chronoEpochTime);

   return resultInMS;
}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241

1 Answers1

0

Why do I have to subtract chronoUserTime - chronoEpochTime instead of using chronoUserTime ?

chronoUserTime is a point in time, a time_point. milliseconds is a duration. A point in time is not a duration and vice versa. In order to convert a point in time to a duration you need a reference point in time and you've here used the common epoch.

Subtracting one time_point from another gives you the duration between those time_points - which in your case is milliseconds since the epoch.

Are there any ways, to perfome this in direct way, like in Qt style addDays, setTime

Yes, you can add a duration to a time_point:

my_time_point += my_duration;    
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108