Getting Epoch Timestamp in C

In C, how to get the epoch timestamp, the number of seconds passed since the epoch?

In C, from man 7 time:

UNIX systems represent time in seconds since the Epoch, 1970-01-01
00:00:00 +0000 (UTC).

A program can determine the calendar time using gettimeofday(2), which
returns time (in seconds and microseconds) that have elapsed since the
Epoch; time(2) provides similar information, but only with accuracy to
the nearest second.

You can use the time() library function to get the epoch timestamp:

On 32-bit POSIX systems:

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

On 64-bit POSIX systems:

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

2 comments:

    1. Hi, the author changed the format a little bit since your comment, but I’m here and nobody else has answered your question, I’ll take a swing at it…

      > how is %un different from %u ?
      The short answer is, caution — for the future! :^O

      In his code, it’s clear he is expecting to print just the timestamp as formatted above, and only that… nothing else. Just an unsigned integer… Like most stuff, the fprintf() function always does exactly what you tell it to do. So here it’s given something to print, and told what type definition it will receive, then the formatting strings. That’s fine, it will do anything we can tell it to do… without double-checking our work :D

      TLDR;
      The ‘n’ specifier means “print nothing”, like a stop gap measure put in place to keep unexpected garbage going to the screen later. Probably a good practice. The time and date functions in author’s example alone probably doesn’t need that ‘n’, but good to have when the time and date stop working in 8,000 years — but then, that’s why he is using a ‘l’ long unsigned integer in his code now ;)

      Hope it helps!
      Also, here’s the site i used for reference:
      https://www.dummies.com/programming/cpp/using-printf-for-output/

      moistrous

Leave a Reply

Your email address will not be published. Required fields are marked *