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

Tim*_*Tim 49 c unix timestamp epoch

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

Dmi*_*roh 59

对于32位系统:

fprintf(stdout, "%u\n", (unsigned)time(NULL)); 
Run Code Online (Sandbox Code Playgroud)

对于64位系统:

fprintf(stdout, "%lu\n", (unsigned long)time(NULL)); 
Run Code Online (Sandbox Code Playgroud)

  • 如果你想要微秒,你应该使用这个函数之一:clock_gettime with CLOCK_MONOTONIC clock id或gettimeofday.但要注意gettimeofday可以返​​回递减时间值. (2认同)
  • `#include <time.h>` (2认同)

Dan*_*her 28

只是转换返回的值 time()

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

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

你想要什么?

$ gcc -Wall -Wextra -pedantic -std=c99 tstamp.c && ./a.out
Timestamp: 1343846167
Run Code Online (Sandbox Code Playgroud)

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

int timespec_get(struct timespec *ts, int base)
Run Code Online (Sandbox Code Playgroud)

不幸的是,到目前为止,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;
}
Run Code Online (Sandbox Code Playgroud)


小智 11

使用二次精度,可以打印从功能中获得tv_sectimeval结构的字段gettimeofday().例如:

#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;
}
Run Code Online (Sandbox Code Playgroud)

编译和运行的示例:

$ gcc -Wall -o test ./test.c 
$ ./test 
Seconds since Jan. 1, 1970: 1343845834
Run Code Online (Sandbox Code Playgroud)

但是请注意,自纪元以来它已经有一段时间了,所以long int这些日子用来适应几秒钟.

还有用于打印人类可读时间的功能.有关详细信息,请参见本手册页 以下是一个例子ctime():

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

int main()
{
    time_t clk = time(NULL);
    printf("%s", ctime(&clk));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

示例运行和输出:

$ gcc -Wall -o test ./test.c 
$ ./test 
Wed Aug  1 14:43:23 2012
$ 
Run Code Online (Sandbox Code Playgroud)


Iva*_*kov 6

#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);
}
Run Code Online (Sandbox Code Playgroud)

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