Home > OS >  Calculating difference between two date-times in C
Calculating difference between two date-times in C

Time:10-16

Summarize Problem

I have two strings in the form YYYY-MM-DD:hh:mm:ss and I would like to calculate the time difference between them. For example, the difference between 2021-10-01:03:44:34 and 2021-10-01:03:44:54, should be 20 seconds. However, the result I get is 0.

Code

I have tried the following:

#include <iomanip>
#include <iostream>

using namespace std;
using timestamp = time_t;

auto StringToTimestamp(const string& timeString) -> timestamp {
  tm tm {};
  stringstream ssBuffer(timeString);
  ssBuffer >> get_time(&tm, "%Y-%b-%d:%H:%M:%S");
 
  cout << tm.tm_year << " " << tm.tm_mon << " " << tm.tm_mday << " "
       << tm.tm_hour << " "<< tm.tm_min  << " " << tm.tm_sec  << " " << endl;

  return  mktime(&tm);
}

int main() {
  string beg = {"2021-10-01:03:44:34"s};
  string end = {"2021-10-01:03:44:54"s};

  timestamp begTm = StringToTimestamp(beg);
  timestamp endTm = StringToTimestamp(end);

  double diff = difftime(endTm, begTm);
  cout << "Time difference is " << diff << endl;
  
  return 0;
}

Output

121 0 0 0 0 0 
121 0 0 0 0 0 
Time difference is 0

Expected Output

2021 10 01 03 44 34 
2021 10 01 03 04 54 
Time difference is 20

Why is the output as such? How can I fix this?

EDIT

I changed this line "%Y-%b-%d:%H:%M:%S" to "%Y-%m-%d:%H:%M:%S" and now the output is

121 9 1 3 44 34 
121 9 1 3 44 54 
Time difference is 20

Why are the year and month "incorrect"?

CodePudding user response:

You use the conversion specifier%b to get the month but it should be %m:

ssBuffer >> get_time(&tm, "%Y-%m-%d:%H:%M:%S");
  • %b - parses the month name, either full or abbreviated, e.g. Oct (non-numeric)
  • %m - parses the month as a decimal number (range [01,12]), leading zeroes permitted but not required

The year and month are correct. 121 is the number of years since 1900 and 9 is the month, zero-based [0,11], which is what's specified for std::tm.

  • Related