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

标签 c++ datetime strftime

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

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/

相关文章:

c++ - 难以理解 C++ 推导

c++ - 当传递无效参数时,函数应该返回什么?

php - 无法设置日期时间

python - 将字符串中的日期列表转换为 Python 中的月、日、年

c++ - malloc 和 new 的实现差异。堆栈实现?

cstdio 或 cstdlib 等 C++ header 引发编译错误

datetime - 如何在 firebase 中获取 firebase 时间

java - 将时分字符串时间转换为 utc,反之亦然

c# - C#Finisar SQLite日期时间比较问题

python - 具有相同区域设置的不同 datetime.strftime 输出