如何根据时间格式指定缓冲区大小

问题描述 投票:0回答:1
以下代码将给定的时间戳转换为UTC,并以给定格式返回

std::string

。我关心的是
std::strftime
需要一定大小作为输入的缓冲区,是否可以根据例如时间格式输入来指定缓冲区大小; 
char

%c

使用转换结构的绝对最小方法是这样的:
c++
1个回答
0
投票
#include <ctime> #include <cstdint> #include <string> std::string convert_timestamp_to_utc(const std::uint64_t timestamp) { const std::time_t time_stamp = static_cast<std::time_t>(timestamp); struct tm buf{}; localtime_r(&time_stamp, &buf); // can buffer size be made dynamic based on the given time format like below %c char time_buf[256]{}; if (std::strftime(time_buf, sizeof(time_buf) - 1, "%c", &buf) != 0) { return std::string(time_buf); } return {}; }

生成的字符串的长度无关紧要,并由标准流量输出操作员处理。

示例在这里
也应该也可以使用

std::put_time

© www.soinside.com 2019 - 2025. All rights reserved.