我想使用以下格式将日期和时间格式化为字符串:
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/