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

前端 未结 7 2056
旧时难觅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:42

    Following code prints with microsecond precision. All we have to do is use gettimeofday and strftime on tv_sec and append tv_usec to the constructed string.

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

提交回复
热议问题