【发布时间】:2012-07-23 23:27:33
【问题描述】:
在 shell 脚本中,当我想要本地时间时,我会做类似的事情
date +%s
从命令行返回当前日期和时间,格式为“1343221713”
我想知道是否有办法在 C 中实现相同的结果
【问题讨论】:
在 shell 脚本中,当我想要本地时间时,我会做类似的事情
date +%s
从命令行返回当前日期和时间,格式为“1343221713”
我想知道是否有办法在 C 中实现相同的结果
【问题讨论】:
比time(3) 更灵活的是gettimeofday(3) 在sys/time.h 中声明
#include <sys/time.h>
#include <stdio.h>
int main(void)
{
struct timeval tv = {0};
gettimeofday(&tv, NULL);
printf("seconds since epoch %ld, microseconds %ld\n", tv.tv_sec, tv.tv_usec);
return 0;
}
【讨论】:
在 C 中使用 time.h 库
示例:
#include <stdio.h>
#include <time.h>
int main()
{
/* Obtain current time as seconds elapsed since the Epoch. */
time_t clock = time(NULL);
/* Convert to local time format and print to stdout. */
printf("Current time is %s", ctime(&clock));
return 0;
}
查看更多示例: http://en.wikipedia.org/wiki/C_date_and_time_functions
【讨论】: