输出时间和日期,格式为:2018-01-26 15:51.159753

Output time and date in the format: 2018-01-26 15:51.159753

本文关键字:2018-01-26 159753 格式 时间 日期 输出      更新时间:2023-10-16

我正在尝试找到以下格式输出当前日期和时间(毫秒(的解决方案: 2018-01-26 15:51:02.159753

我现在拥有的(工作(如下:

#include <iostream>
#include <ctime>
using namespace std;
int main() {
   // current date/time based on current system
   time_t now = time(0);
   // convert now to string form
   char* dt = ctime(&now);
   cout << "The local date and time is: " << dt << endl;
   // convert now to tm struct for UTC
   tm *gmtm = gmtime(&now);
   dt = asctime(gmtm);
   cout << "The UTC date and time is:"<< dt << endl;
}

虽然我没有找到任何方法来重新制作它,以便以我想要的格式输出日期和时间。任何这方面的帮助将不胜感激。

所以你需要使用localtime中的tm,它可能应该像这样初始化:

const auto buz = chrono::system_clock::now().time_since_epoch();
const auto baz = chrono::floor<chrono::seconds>(buz);
const auto bar = chrono::system_clock::to_time_t(chrono::system_clock::time_point(baz));
const auto foo = localtime(&bar);

然后,您可以将其与put_time一起使用:

cout << put_time(foo, "%F %T.") << (buz - baz).count() << endl;

现场示例