如何将C中的unix时间戳作为int?

时间:2012-08-01 18:26:53

标签: c unix timestamp epoch

我想获取当前时间戳并使用fprintf打印出来。

5 个答案:

答案 0 :(得分:55)

对于32位系统:

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

对于64位系统:

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

答案 1 :(得分:26)

只是投射time()

返回的值
#include <stdio.h>
#include <time.h>

int main(void) {
    printf("Timestamp: %d\n",(int)time(NULL));
    return 0;
}

你想要什么?

$ gcc -Wall -Wextra -pedantic -std=c99 tstamp.c && ./a.out
Timestamp: 1343846167

要获得自纪元以来的微秒,从C11开始,便携式方式是使用

int timespec_get(struct timespec *ts, int base)

不幸的是,C11还没有到处可用,所以截至目前,最接近便携式的是使用POSIX函数之一clock_gettimegettimeofday(在POSIX.1-2008中标记为过时,其中建议clock_gettime)。

这两个函数的代码几乎完全相同:

#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;
}

答案 2 :(得分:11)

使用第二个精度,您可以打印tv_sec函数的timeval结构#include <sys/time.h> #include <stdio.h> int main() { struct timeval tv; gettimeofday(&tv, NULL); printf("Seconds since Jan. 1, 1970: %ld\n", tv.tv_sec); return 0; } 字段。例如:

$ gcc -Wall -o test ./test.c 
$ ./test 
Seconds since Jan. 1, 1970: 1343845834

编译和运行的示例:

long int

但是请注意,自纪元以来它已经有一段时间了,所以ctime()这些天被用来适应几秒钟。

还有打印人类可读时间的功能。有关详细信息,请参阅gettimeofday()。以下是使用#include <time.h> #include <stdio.h> int main() { time_t clk = time(NULL); printf("%s", ctime(&clk)); return 0; }

的示例
$ gcc -Wall -o test ./test.c 
$ ./test 
Wed Aug  1 14:43:23 2012
$ 

示例运行&amp;输出:

{{1}}

答案 3 :(得分:0)

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

int main ()
{
   time_t seconds;

   seconds = time(NULL);
   printf("Seconds since January 1, 1970 = %ld\n", seconds);

   return(0);
}

并会得到类似的结果:
自1970年1月1日起的秒数= 1476107865

答案 4 :(得分:0)

重要的一点是要考虑是否基于两个时间戳之间的差异来执行任务,因为如果使用gettimeofday(),甚至在设置时clock_gettime(CLOCK_REALTIME,..)生成时间戳,就会出现奇怪的行为系统时间。

为避免此类问题,请改用clock_gettime(CLOCK_MONOTONIC_RAW, &tms)

相关问题