I would like to get the current timestamp and print it out using fprintf
.
Unix timestamps should be stored as long numbers; if they are store as Java int values, then this leads to a 2038 year problem. 32-bit variables cannot encode times after 03:14:07 UTC on 19 January 2038.
To find the unix current timestamp use the %s option in the date command. The %s option calculates unix timestamp by finding the number of seconds between the current date and unix epoch.
A Unix timestamp is a large integer (the number of seconds since 1970-01-01 00:00:00 UTC), so INT(11) is the correct datatype.
For 32-bit systems:
fprintf(stdout, "%u\n", (unsigned)time(NULL));
For 64-bit systems:
fprintf(stdout, "%lu\n", (unsigned long)time(NULL));
Is just casting the value returned by time()
#include <stdio.h> #include <time.h> int main(void) { printf("Timestamp: %d\n",(int)time(NULL)); return 0; }
what you want?
$ gcc -Wall -Wextra -pedantic -std=c99 tstamp.c && ./a.out Timestamp: 1343846167
To get microseconds since the epoch, from C11 on, the portable way is to use
int timespec_get(struct timespec *ts, int base)
Unfortunately, C11 is not yet available everywhere, so as of now, the closest to portable is using one of the POSIX functions clock_gettime
or gettimeofday
(marked obsolete in POSIX.1-2008, which recommends clock_gettime
).
The code for both functions is nearly identical:
#include <stdio.h> #include <time.h> #include <stdint.h> #include <inttypes.h> int main(void) { struct timespec tms; /* The C11 way */ /* if (! timespec_get(&tms, TIME_UTC)) { */ /* POSIX.1-2008 way */ if (clock_gettime(CLOCK_REALTIME,&tms)) { return -1; } /* seconds, multiplied with 1 million */ int64_t micros = tms.tv_sec * 1000000; /* Add full microseconds */ micros += tms.tv_nsec/1000; /* round up if necessary */ if (tms.tv_nsec % 1000 >= 500) { ++micros; } printf("Microseconds: %"PRId64"\n",micros); return 0; }
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