gpt4 book ai didi

c++ - 在 C++ 中用小数秒格式化日期和时间

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:50:03 28 4
gpt4 key购买 nike

我想使用以下格式将日期和时间格式化为字符串:

20130630-03:11:45.862

我可以通过使用 strftime 来完成大部分工作,但是没有明确的方法可以在最后实现小数秒。

我当前的代码是:

time_t rawtime;
time(&rawtime);
tm* timeinfo = localtime(&rawtime);
char buffer[80];
strftime(buffer, 80, "%G%m%d-%I:%M:%S", timeinfo);

这会产生没有小数秒部分的值。

但最终我只想以这种格式获得日期的字符串版本,而不关心它需要什么 API。

我在 Linux 上使用 g++ 以防相关。

最佳答案

如果您不关心 API,可以使用 boost::date_time它是 time_facet .

到目前为止的简短示例:

// setup facet and zone
// this facet should result like your desired format
std::string facet="%Y%m%d-%H:%M:%s";
std::string zone="UTC+00";

// create a facet
boost::local_time::local_time_facet *time_facet;
time_facet = new boost::local_time::local_time_facet;

// create a stream and imbue the facet
std::stringstream stream(std::stringstream::in | std::stringstream::out);
stream.imbue(std::locale(stream.getloc(), time_facet));

// create zone
boost::local_time::time_zone_ptr time_zone;
time_zone.reset(new boost::local_time::posix_time_zone(zone));

// write local from calculated zone in the given facet to stream
stream << boost::local_time::local_microsec_clock::local_time(time_zone);

// now you can get the string from stream
std::string my_time = stream.str();

这个例子可能不完整,因为我从我的代码中复制了一些代码,但我希望你明白了。

使用 facet,您可以设置格式。 %s(小 s 有,大 S 没有分形)设置分形秒数。您可以在文档中阅读此内容 facet format .

时区用于计算您的本地机器时间到正确的时区。

关于c++ - 在 C++ 中用小数秒格式化日期和时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17386186/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com