【问题标题】:C truncate HH:MM:SS from ctime value, ctimeC 从 ctime 值 ctime 截断 HH:MM:SS
【发布时间】:2013-01-12 13:38:48
【问题描述】:

我有这个 unix 时间戳,当使用 ctime 转换时显示为 Thu Mar 26 15:30:26 2007,但我只需要 Thu Mar 26 2007

如何更改或截断以消除时间 (HH:MM:SS)?

【问题讨论】:

    标签: c unix ctime


    【解决方案1】:

    既然你有一个time_t 值,你可以使用localtime()strftime()

    #include <time.h>
    #include <stdio.h>
    
    int main(void)
    {
        time_t t = time(0);
        struct tm *lt = localtime(&t);
        char buffer[20];
        strftime(buffer, sizeof(buffer), "%a %b %d %Y", lt);
        puts(buffer);
        return(0);
    }
    

    或者,如果您觉得必须使用ctime(),那么:

    #include <time.h>
    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
        time_t t = time(0);
        char buffer[20];
        char *str = ctime(&t);
        memmove(&buffer[0],  &str[0],  11);
        memmove(&buffer[11], &str[20],  4);
        buffer[15] = '\0';
        puts(buffer);
        return(0);
    }
    

    【讨论】:

      【解决方案2】:

      来自strptime()的手册页:

      以下示例演示了strptime()strftime() 的使用。

         #include <stdio.h>
         #include <time.h>
      
         int main() {
                 struct tm tm;
                 char buf[255];
      
                 strptime("2001-11-12 18:31:01", "%Y-%m-%d %H:%M:%S", &tm);
                 strftime(buf, sizeof(buf), "%d %b %Y %H:%M", &tm);
                 puts(buf);
                 return 0;
         }
      

      根据自己的需要进行调整。

      【讨论】:

        猜你喜欢
        • 2012-02-24
        • 2012-05-18
        • 1970-01-01
        • 2011-08-27
        • 2012-09-11
        • 1970-01-01
        • 2011-08-02
        • 2021-03-10
        • 2011-06-12
        相关资源
        最近更新 更多