Question

I am wondering which data type is most appropriate to store a date? I am reading variables from the command line through argv:

int main (int argc, char *argv[]) {
    if (argc!=19) {
        usage();
        exit(1);
    }
        int id = atoi(argv[1]);
        int date = atoi(argv[2]);
}

Am I right in assuming that I can store it as an int? or is char better? even keep it as a string? I'm not sure on the best practice for this.

Was it helpful?

Solution 2

Parse the input into elements of a struct tm, then convert into time_t

#include <stdlib.h>
#include <time.h>

char input[] = "2003-06-16";

struct tm temp = {0};
temp.tm_mday = strtol(input + 8, NULL, 10); // needs error checking
temp.tm_mon = strtol(input + 5, NULL, 10) - 1; // needs error checking
temp.tm_year = strtol(input, NULL, 10) - 1900; // needs error checking

time_t unix_seconds = mktime(&temp);

Apparently you just need a temporary holding space for the date. So keep it in the same format as input and output: keep it as a string.

OTHER TIPS

The C documentation about date indicates that you can use the time_t type which expresses a date with the number of seconds elapsed since a specific date called Epoch.

Where Epoch is : 00:00, Jan 1 1970 UTC

If I wished to use date without using this time_t lib, I would use long integer.

With strptime(), you get the possibility to parse a date/time string neatly. As this gives you the data in the form of a struct tm, you might want to use this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top