user11745417
user11745417

Reputation:

How to convert C date string into an integer?

I have dates as strings in this format:

YYYY-MM-DD (2021-07-01, 2021-02-21 etc.)

Now I want to compare them, and the best solution I can think of is converting all of those dates into some number (like unix time), but I don't know how to do it.

It has to be precise with days (so that 2021-01-01 < 2021-01-02).

I found strptime() function on the Internet, but I'm a Windows user (CLion), so I can't use that.

Is it possible to do it in a simple way? Leap years have to accounted for.

EDIT: My input data look like this:

char date1[] = "2021-01-07";
char date2[] = "2021-01-14";
char date3[] = "2021-01-20"; etc.

How I want to use them:

if (date1 < date2 < date3){
    // return "true" if date2 is in the interval (Pseudocode ofc)
    return true;
}

Upvotes: 1

Views: 2326

Answers (2)

chux
chux

Reputation: 153488

How to convert C date string into an integer?

Compare correctly

As OP's date strings are in chronological and lexicographical order, a conversion is not needed (unless one has negative years).

// if (date1 < date2 < date3){ 
if (strcmp(date1, date2) < 0 && strcmp(date2, date3) < 0) {

Convert string to time_t

If one wants to still convert, use sscanf() to parse the string. Pay special attention to possible errors.

Some somewhat tested code:

#include <time.h>

time_t YMD_to_time(const char *ymd) {
  if (ymd == NULL) {
    return (time_t)-1;
  }

  struct tm tm = {0}; // Important: initialize all members to 0
  int n = 0;
  sscanf(ymd, "%4d-%2d-%2d %n", &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &n);

  // Scan incomplete or extra junk?
  if (n == 0 || ymd[n]) {
    return (time_t)-1; // Mal-formed string
  }

  // Could add extra checks for months/days outside primary range, spaces in string, etc.

  // Adjust ranges as struct tm uses different references
  tm.tm_year -= 1900;
  tm.tm_mon--;
  tm.tm_isdst = -1; // Important to get right time for Year-Month-Day 00:00:00 _local time_

  // The following conversion assumes tm is in local time.
  return mktime(&tm); // This may return -1;
}

Usage

time_t t1 = YMD_to_time(date1);
time_t t2 = YMD_to_time(date2);
time_t t3 = YMD_to_time(date3);
if (t1 == -1 || t2 == -1 || t3 == -1) return times_are_not_comparable
if (t1 < t2 && t2 < t3) return times_are_in_order;
return times_not_in_order;

Upvotes: 3

0___________
0___________

Reputation: 67536

if (date1 < date2 < date3) it will never work.

To convert to integers learn about sscanf function

Upvotes: -1

Related Questions