使用Strftime格式化DateTime
Using Strftime to format DateTime
我正在开发一个函数,将输入时间戳格式化为输入格式。
std::string 1stformat = "dd - MM - yyyy HH 'Hours' mm 'Minutes' ss 'Seconds' SSS 'Miliseconds –' a '– Time Zone: ' Z '-' zzzz";//will not print anything
std::string 2ndformat = "'This took about' h 'minutes and' s 'seconds.'";//will print out
格式化后
char date_string[100];
strftime(date_string, 50, format.c_str(), curr_tm);
我的问题是,有时输入格式太长,导致缓冲区date_string
不足以满足要求。在过去的三周里,我刚开始学习C++,所以对此我没有太多的经验。
strftime()
的包装器,根据需要增加缓冲区,直到它足够大,可以容纳所需的时间字符串:
#include <ctime>
#include <iostream>
#include <memory>
#include <string>
std::string safe_strftime(const char *fmt, const std::tm *t) {
std::size_t len = 10; // Adjust initial length as desired. Maybe based on the length of fmt?
auto buff = std::make_unique<char[]>(len);
while (std::strftime(buff.get(), len, fmt, t) == 0) {
len *= 2;
buff = std::make_unique<char[]>(len);
}
return std::string{buff.get()};
}
int main() {
std::time_t now;
std::time(&now);
std::cout << safe_strftime("The date is %Y-%m-%d", std::localtime(&now))
<< 'n';
return 0;
}
不幸的是,std::strftime()
的接口不如std::snprintf()
的接口有用,因为如果缓冲区太小,它会返回0,而不是将要写入的字符数。我们需要试探性地增加缓冲区大小,然后重试,可能是这样的:
#include <ctime>
#include <string>
#include <vector>
std::string time_to_string(const char *format, const std::tm* time)
{
// first try with an on-stack buffer (fast path)
char buf[200];
auto written = std::strftime(buf, sizeof buf, format, time);
if (written > 0) {
return buf;
}
// now, iterate with an allocated buffer
auto len = sizeof buf;
std::vector<char> v;
do {
v.resize(len *= 2);
written = std::strftime(v.data(), v.size(), format, time);
} while (written == 0);
return {v.data(), written};
}
相关文章:
- C++格式化输出问题
- 格式化浮点值:返回默认值
- 自动格式化程序> >更改为>>
- 如何从C++中的格式化字符串派生整数?
- 将从格式化文本文件读取的文本数据存储到链表
- 在不使用系统的情况下从C++应用程序格式化 Linux 中的 SD 卡
- 高精度双精度的 Sprintf 格式化问题
- 如何在 c++ 中格式化和访问 2D 矢量数组中的数据
- 叮当格式化程序多行格式配置错误
- 如何格式化我的文本文件以使其不会一遍又一遍地重复同一行?
- 从函数(不抛出函数)返回异常以进行消息格式化?
- 从格式化输入操作中获取读取字符数
- 如何在MySQL Connector/C++ 8.0中使用DATETIME?
- 如何从标准输入中检测格式化输入错误?
- 无法从 spdlog 中格式化参数
- 格式化时间 c++ dd/mm/yyyy hh:ss.
- 如何正确格式化csv文件?
- 如何使用xdevapi从mysql获取DateTime
- 使用Strftime格式化DateTime
- 如何在C (例如System.DateTime.NOW In .net中)中格式化当前的DateTime