For a small todo program that I am writing, I have timestamps that are of this form
time_t t = time(NULL);
and are saved every time a task is entered to denote the time that it was entered.
I want to store the tasks to a plain text file, so that the state can be saved and restored. How should I store the timestamps to the text file and how should I get them back in my program after reading the text file?
The time() function is defined in time. h (ctime in C++) header file. This function returns the time since 00:00:00 UTC, January 1, 1970 (Unix timestamp) in seconds. If second is not a null pointer, the returned value is also stored in the object pointed to by second.
timestamp, a C code which prints the YMDHMS date as a timestamp. This is useful when documenting the run of a program. By including a timestamp, the output of the program will always contain a clear indication of when it was created.
C Program to Display the current Date and Time The C library function char *ctime(const time_t *timer) returns a string representing the localtime based on the argument timer. The returned string has the following format: Www Mmm dd hh:mm:ss yyyy.
Convert the time_t to struct tm using gmtime(), then convert the struct tm to plain text (preferably ISO 8601 format) using strftime(). The result will be portable, human readable, and machine readable.
To get back to the time_t, you just parse the string back into a struct tm and use mktime().
For reference:
Code sample:
// Converting from time_t to string
time_t t = time(NULL);
struct tm *ptm = gmtime(&t);
char buf[256];
strftime(buf, sizeof buf, "%F %T", ptm);
// buf is now "2015-05-15 22:55:13"
// Converting from string to time_t
char *buf = "2015-05-15 22:55:13";
struct tm tm;
strptime(buf, "%F %T", &tm);
time_t t = mktime(&tm);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With