What is the best datatype to store date in C, to then output into a csv file?

StackOverflow https://stackoverflow.com/questions/23648912

  •  22-07-2023
  •  | 
  •  

문제

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.

도움이 되었습니까?

해결책 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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top