C++ 不使用C+,输出时间和日期(带分数时间)+;11

C++ 不使用C+,输出时间和日期(带分数时间)+;11,c++,C++,我正试图找到一种以以下格式输出当前日期和时间(以毫秒为单位)的解决方案:2018-01-28 15:51:02.159 这可以通过使用C++17和chrono::floor或C++11std::chrono::duration\u cast来解决 不幸的是,我不能使用C++17或C++11-还有其他不太高级的选项吗?如果没有,我将非常感谢您在不使用小数时间的情况下提供正确格式的帮助,如:2018-01-28 15:51:02 非常感谢您的帮助 使用和此帖子: < C++ > C++继承了它的时间

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

这可以通过使用C++17和
chrono::floor
或C++11
std::chrono::duration\u cast来解决

不幸的是,我不能使用C++17或C++11-还有其他不太高级的选项吗?如果没有,我将非常感谢您在不使用小数时间的情况下提供正确格式的帮助,如:2018-01-28 15:51:02

非常感谢您的帮助

使用和此帖子:


< C++ > C++继承了它的时间单位,保证的解决方案是回到C库(不记得看到纯C++版本……这和我能保持的C++一样多):

#包括
#包括//std::setw()。。。
#包括
#包括//gettimeofday()和朋友
内部主(空)
{
结构时间值电视;
struct tm local_tm;
字符打印时间[30];
gettimeofday(&tv,NULL);
localtime\u r(&tv.tv\u sec,&local\u tm);
strftime(打印时间、打印时间大小、%Y-%m-%d%H:%m:%S.,&local\u tm);

cout cppreference是你的朋友:非常感谢!你可能知道这有多大的计算量吗?请始终注意通用的“计算时间”估计,因为它们可能非常具体(点击…编写一些基准测试并在你的环境中运行它们..确保你没有测试缓存)。getimeofday()和localtime_r()会很快。gmtime_r()可以更快,因为它不需要摆弄时区,但您可以得到UTC(GMT)时间,我倾向于在服务器aps中使用UTC(GMT)时间。如果您不使用strftime()来打印整数,则可以做得更好。还有一个问题,我的gcc返回一个
警告:从“\u suseconds\u t{aka long int}”转换为“int”可能会改变其值[-Wconversion]int milli=curTime.tv\u usec/1000;
您可能知道为什么/如何解决它吗?是的,感谢您指出这一点,请尝试用c标准替换标题
。请参阅编辑后的答案。
#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
#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;
}