【问题标题】:How to format a time stamp in C如何在C中格式化时间戳
【发布时间】:2016-02-22 22:12:14
【问题描述】:

我试图弄清楚如何使用下面的函数获取当前时间戳,但我想对其进行格式化,以便在输出时显示 4:30:23 之类的时间。最终我想在运行算法之前和之后减去时间戳。

struct timeval FindTime() {     
    struct timeval tv;    
    gettimeofday(&tv,NULL);
    return tv;
}

int main() { 
    printf("%ld\n",FindTime());
    return0;
}

当前输出格式: 1456178100

【问题讨论】:

标签: c strftime


【解决方案1】:

这可能是您需要的吗?

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

struct setClock{
    int hour;
    int minutes;
    int seconds;
};

struct setClock currTime(void);
void timeCheck(struct setClock myClock[2]);

int main(void){
    struct setClock myClock[2];

    myClock[0] = currTime();
    printf("Start Time: %d:%d:%d\n\n", myClock[0].hour, myClock[0].minutes, myClock[0].seconds );

    sleep(5);
    /*  CODE HERE  */

    myClock[1] = currTime();
    printf("End Time:   %d:%d:%d\n", myClock[1].hour, myClock[1].minutes, myClock[1].seconds );

    timeCheck(myClock);

    return 0;

}

struct setClock currTime(void){
    struct setClock ret;
    struct tm *tm;
    time_t myTime;

    myTime=time(NULL);
    tm=localtime(&myTime);

    ret.hour = tm->tm_hour;
    ret.minutes = tm->tm_min;
    ret.seconds = tm->tm_sec;

    return ret;
}

void timeCheck(struct setClock myClock[2]){
    int hour;
    int minute;
    int second;

    time_t end, start;
    double diff;

    start = (time_t)((myClock[0].hour * 60 + myClock[0].minutes) * 60 + myClock[0].seconds) ;
    end   = (time_t)((myClock[1].hour * 60 + myClock[1].minutes) * 60 + myClock[1].seconds) ;

    if( end < start ){
        end += 24 * 60 * 60 ;
    }

    diff = difftime(end, start);

    hour = (int) diff / 3600;
    minute = (int) diff % 3600 / 60;
    second = (int) diff % 60;

    printf("\n\n");
    printf("The elapsed time is  %d Hours - %d Minutes - %d Seconds.\n", hour, minute, second);
}

输出:

Start Time: 23:19:18

End Time:   23:19:23


The elapsed time is  0 Hours - 0 Minutes - 5 Seconds

【讨论】:

  • 是的,太棒了!我只是好奇是否有更简单的代码更少的方法。
  • @aaaa 如果您认为我的回答对您来说还可以,请采纳。
  • 如何减去开始时间和结束时间?
【解决方案2】:

阅读strftime

我猜你想要%T

【讨论】:

    【解决方案3】:

    您可以使用此代码和 String 函数来捕获时间

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    #include <String.h>
    
    
    int main()
    {
     time_t timeLine;
    struct tm * timeInfo;
    
    time ( &timeLine );
    timeInfo = localtime ( &timeLine );
    printf ( "%s", asctime (timeInfo) );
    
    return 0;
    }
    

    【讨论】:

    • 你的代码产生了这个Mon Feb 22 23:48:51 2016,而OP只需要这个23:48:51
    猜你喜欢
    • 2011-01-10
    • 1970-01-01
    • 2012-10-23
    • 1970-01-01
    • 2019-02-17
    • 2012-06-24
    • 1970-01-01
    相关资源
    最近更新 更多