Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the unix timestamp in C as an int?

I would like to get the current timestamp and print it out using fprintf.

like image 903
Tim Avatar asked Aug 01 '12 18:08

Tim


People also ask

Can Unix time be stored in int?

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.

How do I display a Unix timestamp?

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.

What datatype is used to store Unix timestamps?

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.


2 Answers

For 32-bit systems:

fprintf(stdout, "%u\n", (unsigned)time(NULL));  

For 64-bit systems:

fprintf(stdout, "%lu\n", (unsigned long)time(NULL));  
like image 152
Dmitry Poroh Avatar answered Sep 21 '22 08:09

Dmitry Poroh


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; } 
like image 28
Daniel Fischer Avatar answered Sep 20 '22 08:09

Daniel Fischer