How to format a time stamp in C

人盡茶涼 提交于 2019-11-28 12:06:20

问题


I'm trying to figure out how to get the current timestamp using the function below but I want to format it so that it displays the time like 4:30:23 on output. Eventually I want to subtract the time stamps before and after I run an algorithm.

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

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

Current output format: 1456178100


回答1:


Could be this what you need?

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

Output:

Start Time: 23:19:18

End Time:   23:19:23


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



回答2:


Read up on strftime.

I guess you want %T?




回答3:


you can use this code with using the String function to catch just a time

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


来源:https://stackoverflow.com/questions/35564970/how-to-format-a-time-stamp-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!