c++ clock_gettime() and daylight savings

前端 未结 4 1650
终归单人心
终归单人心 2021-01-23 02:07

I am using clock_gettime() in my C++ program to get the current time. However, the return value is seconds since epoch in UTC. This code can get messed up in my time zone durin

4条回答
  •  遥遥无期
    2021-01-23 02:18

    Realize that time also reports seconds since the beginning of 1970 (in a time_t). If you take the tv_sec member of the timespec and pass it to localtime or localtime_r, you should get what you want.

    timespec tsv;
    clock_gettime(CLOCK_REALTIME, &tsv);
    time_t t = tsv.tv_sec; // just in case types aren't the same
    tm tmv;
    localtime_r(&t, &tmv); // populate tmv with local time info
    

    And you can deal with the tv_nsec member of the timespec however you wish.

提交回复
热议问题