如何将Chrono :: time_point格式化为字符串
How to format a chrono::time_point as a string
我需要在C 中获取当前日期和时间。我可以使用chrono
获取system time
,但我还需要将其保存在JSON文件中。此外,我尝试过的计时时间给出以下格式:
auto time = std::chrono::system_clock::now();
输出:
Thu Oct 11 19:10:24 2012
但我需要以下格式的日期时间格式:
2016-12-07T00:52:07
也需要在字符串中的这个日期时间,以便可以将其保存在JSON文件中。任何人都可以提出一种实现这一目标的好方法。谢谢。
最简单的方法是使用霍华德·辛南特(Howard Hinnant(的免费,开源,仅标题日期。H:
#include "date/date.h"
#include <iostream>
#include <string>
int
main()
{
using namespace date;
using namespace std::chrono;
auto time = system_clock::now();
std::string s = format("%FT%T", floor<seconds>(time));
std::cout << s << 'n';
}
此库是新的C 20,Chrono扩展的原型。尽管在C 20中,格式的细节可能会稍有变化,以使其与预期的C 20 fmt
库。
#include <iostream>
#include <chrono>
#include <ctime>
std::string getTimeStr(){
std::time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::string s(30, ' ');
std::strftime(&s[0], s.size(), "%Y-%m-%d %H:%M:%S", std::localtime(&now));
return s;
}
int main(){
std::cout<<getTimeStr()<<std::endl;
return 0;
}
相关文章:
- C++格式化输出问题
- 格式化浮点值:返回默认值
- 自动格式化程序> >更改为>>
- 如何从C++中的格式化字符串派生整数?
- 将从格式化文本文件读取的文本数据存储到链表
- 在不使用系统的情况下从C++应用程序格式化 Linux 中的 SD 卡
- 高精度双精度的 Sprintf 格式化问题
- 如何在 c++ 中格式化和访问 2D 矢量数组中的数据
- 叮当格式化程序多行格式配置错误
- 如何格式化我的文本文件以使其不会一遍又一遍地重复同一行?
- 从函数(不抛出函数)返回异常以进行消息格式化?
- 从格式化输入操作中获取读取字符数
- 如何从标准输入中检测格式化输入错误?
- 无法从 spdlog 中格式化参数
- 格式化时间 c++ dd/mm/yyyy hh:ss.
- 如何正确格式化csv文件?
- 格式化sqlite3_exec结果
- Qt5 部署"procedure entry point could not be located"
- 使用 std::locale 格式化法语数字时无效的 UTF-8 数据
- C++逐步格式化字符串