使用自定义时区将 boost::p osix_time::p time 转换为字符串
Convert boost::posix_time::ptime to string using custom time zone
我有一个boost::posix_time::ptime
实例,想使用给定的boost::local_time::time_zone_ptr
实例将其转换("格式化"(为字符串。下面是一个测试程序,显示了我目前拥有的内容。它将ptime
转换为local_date_time
,根据我的理解,除了时间信息外,还表示时区。
在 2011-08-18 12:00:00 UTC 运行此程序时,我希望输出2011-08-18 14.00.00 UTC+02:00
。相反,它打印2011-08-18 12:00:00 UTC+00:00
.即相对于打印的时区,打印的时间是正确的,但它不在我用于创建boost::local_time::local_date_time
实例的时区中。
我目前使用此问题中建议的技术来使用自定义格式字符串。
#include <iostream>
#include <ctime>
#include <boost/date_time.hpp>
int main(int argc, char ** argv) {
using namespace std;
// Get current time, as an example
boost::posix_time::ptime dt = boost::posix_time::microsec_clock::universal_time();
// Create a time_zone_ptr for the desired time zone and use it to create a local_date_time
boost::local_time::time_zone_ptr zone(new boost::local_time::posix_time_zone("EST"));
boost::local_time::local_date_time dt_with_zone(dt, zone);
std::stringstream strm;
// Set the formatting facet on the stringstream and print the local_date_time to it.
// Ownership of the boost::local_time::local_time_facet object goes to the created std::locale object.
strm.imbue(std::locale(std::cout.getloc(), new boost::local_time::local_time_facet("%Y-%m-%d %H:%M:%S UTC%Q")));
strm << dt_with_zone;
// Print the stream's content to the console
cout << strm.str() << endl;
return 0;
}
我应该如何将local_date_time
实例转换为字符串,以便使用time_zone_ptr
实例指定的时区表示字符串中的日期?
我认为 boost 不知道时区说明符。取代
new boost::local_time::posix_time_zone("EST")
在您的代码中由
new boost::local_time::posix_time_zone("EST-05:00:00")
一切正常。如果要使用通用标准名称,则必须按照提升文档中的说明创建时区数据库。
相关文章:
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- C++自定义比较函数
- 如何比较自定义类的std::变体
- std::设置自定义比较器
- 如何正确实现和访问运算符的各种自定义枚举器
- flutter:即使shouldRepaint()返回true,自定义画家也不会重新绘制
- 自定义先决条件对移动分配运算符有效吗
- 使用VS Code和CMake Tools运行自定义命令
- 如何创建从Maya(或类似程序)到虚幻引擎的自定义数据导出插件
- std::ranges::elements_view,用于自定义类似元组的数据
- 跟随整数索引列表的自定义类迭代器
- 参数化自定义CMake工具链
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 如何在自定义类中启用'auto loops'?
- 使用QJsEngine在Qt中注册自定义类型
- Qt自定义QPush按钮未显示在布局上
- 自定义对象的dlib序列化在gcc中失败
- 自定义 Python 构建 - time.so:未定义的符号:PyExc_ValueError
- 使用自定义时区将 boost::p osix_time::p time 转换为字符串