Ian
Ian

Reputation: 3898

How to get a Unix timestamp for C (in double or float)

How can I get a Unix time stamp for C, specifically showing decimal places. All the answers I have found elsewhere return an integer.

Upvotes: 1

Views: 8601

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753525

The time() function returns an integer only. Both gettimeofday() and clock_gettime() return structures (different structures) with seconds and subseconds (microseconds for gettimeofday() and nanoseconds for clock_gettime()). You'd have to do an appropriate (but simple) computation to return that as a double.

There's no point in returning a current Unix timestamp as a float; you'd only get values accurate to a couple of minutes or so.

POSIX has officially deprecated gettimeofday(). However, Mac OS X for one does not have clock_gettime(), so you're likely to find gettimeofday() is more widely available.

#include <time.h>
#include <stdio.h>

int main(void)
{
    long  t0 = time(0);
    float f0 = t0;
    float f1;
    float f2;

    long d_pos = 0;
    long d_neg = 0;

    while ((f1 = t0 + d_pos) == f0)
        d_pos++;
    while ((f2 = t0 + d_neg) == f0)
        d_neg--;

    printf("t0 = %ld; f0 = %12.0f; d_pos = %ld (f1 = %12.0f); d_neg = %ld (f2 = %12.0f)\n",
        t0, f0, d_pos, f1, d_neg, f2);
    return 0;
}

Sample output:

t0 = 1385638386; f0 =   1385638400; d_pos = 79 (f1 =   1385638528); d_neg = -51 (f2 =   1385638272)

Upvotes: 5

Related Questions