How to print time_t in a specific format?

前端 未结 1 1462
春和景丽
春和景丽 2020-12-17 00:08

ls command prints time in this format:

Aug 23 06:07 

How can I convert time received from stat()\'s mtime() int

相关标签:
1条回答
  • 2020-12-17 00:42

    Use strftime (you need to convert time_t to struct tm* first):

    char buff[20];
    struct tm * timeinfo;
    timeinfo = localtime (&mtime);
    strftime(buff, sizeof(buff), "%b %d %H:%M", timeinfo);
    

    Formats:

    %b - The abbreviated month name according to the current locale.
    
    %d - The day of the month as a decimal number (range 01 to 31).
    
    %H - The hour as a decimal number using a 24-hour clock (range 00 to 23).
    
    %M - The minute as a decimal number (range 00 to 59).
    

    Here is the full code:

    struct stat info; 
    char buff[20]; 
    struct tm * timeinfo;
    
    stat(workingFile, &info); 
    
    timeinfo = localtime (&(info.st_mtime)); 
    strftime(buff, 20, "%b %d %H:%M", timeinfo); 
    printf("%s",buff);
    
    0 讨论(0)
提交回复
热议问题