输出时间和日期与小数时间而不使用C ++ 11

时间:2018-01-28 20:37:38

标签: c++

我正在尝试使用以下格式找到输出当前日期和时间(以毫秒为单位)的解决方案:2018-01-28 15:51:02.159

这可以使用C ++ 17和chrono::floor<chrono::seconds>或C ++ 11 std::chrono::duration_cast<std::chrono::seconds>

来解决

不幸的是我无法使用C ++ 17或C ++ 11 - 还有其他不太高级的选项吗?如果没有,我会感谢一些帮助,在没有分数时间的情况下正确格式化,如下所示:2018-01-28 15:51:02

非常感谢帮助!

2 个答案:

答案 0 :(得分:1)

使用localtime和此帖Getting current time with milliseconds

#include <time.h>
#include <cstdio>  // handle type conversions 
#include <sys/time.h>

int main (void) {

    timeval curTime;
    gettimeofday(&curTime, NULL);
    int milli = curTime.tv_usec / 1000;

    char buffer [80];
    strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", localtime(&curTime.tv_sec));

    char currentTime[84] = "";
    sprintf(currentTime, "%s.%d", buffer, milli);
    printf("current date time: %s \n", currentTime);

    return 0;
}

输出:

current date time: 2018-01-28 14:45:52.486

答案 1 :(得分:1)

由于C ++从C继承了它的时间单元,保证解决方案是回退到C库(不记得看到纯C ++版本......这样可以保留尽可能多的C ++):

#include <iostream>
#include <iomanip>                // std::setw()...
#include <cstdlib>

#include <sys/time.h>             // gettimeofday() and friends


int main(void)
{
     struct timeval  tv;
     struct tm       local_tm;
     char            print_time[30];

     gettimeofday(&tv,NULL);
     localtime_r( &tv.tv_sec, &local_tm );
     strftime( print_time, sizeof print_time, "%Y-%m-%d %H:%M:%S.", &local_tm );


     std::cout << print_time  << std::setw(3) << std::setfill('0') << ( tv.tv_usec + 500 ) / 1000 << std::endl;

     return EXIT_SUCCESS;
}

您当然可以通过一系列 setw()调用跳过 strftime(),但我认为 strftime()更清晰。