jul*_*anc 1 c time gettimeofday
我正在尝试以秒精度打印ISO-8601中的时间.YYYY-MM-DDTHH:MM:SS.S
这是我的代码:
#include <sys/time.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void milli_time(char* dest, struct timeval* t)
{
struct tm* timeInfo;
strftime(dest, 22, "%Y-%m-%dT%t", localtime(&t->tv_sec));
printf("%s\n", dest);
fflush(stdout);
char deciTime[3];
sprintf(deciTime, ".%lu", ((t->tv_usec)/100000ul));
strcat(dest, deciTime);
}
int main()
{
struct timeval* theTime;
char timeString[32];
gettimeofday(theTime, NULL);
printf("%lu.%lu\n", theTime->tv_sec, theTime->tv_usec);
milli_time(timeString, theTime);
printf("%s\n", timeString);
fflush(stdout);
}
Run Code Online (Sandbox Code Playgroud)
每次运行它的输出是:
134520616.3077826840
1974-04-06T17:50:16
1974-04-06T17:50:16.30778
Run Code Online (Sandbox Code Playgroud)
我注意到的另一件事是tv_usec超过一百万.
更改struct timeval* theTime到struct timeval theTime和更新它的相应的参考:
gettimeofday(&theTime, NULL);
// etc
Run Code Online (Sandbox Code Playgroud)
这样您就可以为结构分配空间,而不仅仅是指向结构的指针.当我尝试在我的机器上运行它时,您的代码会出现段错误.
| 归档时间: |
|
| 查看次数: |
594 次 |
| 最近记录: |