How to print time in format: 2009‐08‐10 18:17:54.811

前端 未结 7 2053
旧时难觅i
旧时难觅i 2020-11-27 12:24

What\'s the best method to print out time in C in the format 2009‐08‐10 
18:17:54.811?

7条回答
  •  孤独总比滥情好
    2020-11-27 12:58

    The above answers do not fully answer the question (specifically the millisec part). My solution to this is to use gettimeofday before strftime. Note the care to avoid rounding millisec to "1000". This is based on Hamid Nazari's answer.

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

提交回复
热议问题