如何打印时间格式:2009-08-10 18:17:54.811

Dom*_*mra 84 c time

在格式中以C打印时间的最佳方法是2009?08?10 ?18:17:54.811什么?

Ham*_*ari 98

使用strftime().

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

int main()
{
    time_t timer;
    char buffer[26];
    struct tm* tm_info;

    time(&timer);
    tm_info = localtime(&timer);

    strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", tm_info);
    puts(buffer);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

对于毫秒部分,请看一下这个问题.如何使用ANSI C测量时间(以毫秒为单位)?

  • 最好比更短更长:-) (11认同)
  • 答案在至少一种情况下(Linux)绝对是错误的,因为localtime()使用的“ struct tm”不包含秒以下的任何时间信息。取而代之的是,gettimeofday()使用的“ struct timeval”具有微秒,除以1000会得到毫秒。所有这些批评确实是错误的和误导性的!除非有人报告使用哪种架构,否则您将使用“ struct tm”获得第二个以下的时间详细信息。 (4认同)

Chr*_*ris 27

上述答案并未完全回答这个问题(特别是毫秒级部分).我的解决方案是在strftime之前使用gettimeofday.请注意避免将millisec舍入为"1000".这是基于Hamid Nazari的回答.

#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <math.h>

int main() {
  char buffer[26];
  int millisec;
  struct tm* tm_info;
  struct timeval tv;

  gettimeofday(&tv, NULL);

  millisec = lrint(tv.tv_usec/1000.0); // Round to nearest millisec
  if (millisec>=1000) { // Allow for rounding up to nearest second
    millisec -=1000;
    tv.tv_sec++;
  }

  tm_info = localtime(&tv.tv_sec);

  strftime(buffer, 26, "%Y:%m:%d %H:%M:%S", tm_info);
  printf("%s.%03d\n", buffer, millisec);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为缓冲区[24]就够了,原因如下,YYYY:MM:DD HH:MM:SS.mmm +'\ 0',是24. (2认同)
  • user3624334:不,你不明白代码。只有一个时间请求。我假设您指的是本地时间调用 - 它只是重新格式化 gettimeofday 的输出。 (2认同)

pax*_*blo 10

time.h定义一个strftime函数,它可以为您提供以下内容的文本表示time_t:

#include <stdio.h>
#include <time.h>
int main (void) {
    char buff[100];
    time_t now = time (0);
    strftime (buff, 100, "%Y-%m-%d %H:%M:%S.000", localtime (&now));
    printf ("%s\n", buff);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但这不会给你亚秒级的分辨率,因为那是不可用的time_t.它输出:

2010-09-09 10:08:34.000
Run Code Online (Sandbox Code Playgroud)

如果你真的受到规范的限制,并且不想要白天和小时之间的空间,只需将其从格式字符串中删除即可.

  • 我的一个朋友(当然不是我)曾经使用了类似的技巧 - 他们保持静态包含最后一秒和"毫秒".如果第二次没有改变,他们只是在1到200之间添加一个随机值到毫秒(确保它当然没有超过999 - 兰特()的实际最大值总是最小值200和一半到999的距离).第二个确实改变了,他们只是在添加之前将millisec设置为0.好看似随机但正确排序毫秒,客户不是更明智的:-) (3认同)

Nat*_*raj 7

以下代码以微秒精度打印。我们所要做的就是使用gettimeofdayand strftimeontv_sec并附tv_usec加到构造的字符串。

#include <stdio.h>
#include <time.h>
#include <sys/time.h>
int main(void) {
    struct timeval tmnow;
    struct tm *tm;
    char buf[30], usec_buf[6];
    gettimeofday(&tmnow, NULL);
    tm = localtime(&tmnow.tv_sec);
    strftime(buf,30,"%Y:%m:%dT%H:%M:%S", tm);
    strcat(buf,".");
    sprintf(usec_buf,"%dZ",(int)tmnow.tv_usec);
    strcat(buf,usec_buf);
    printf("%s",buf);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)