【问题标题】:what is the best practice for storing date and time in class/object?在类/对象中存储日期和时间的最佳做法是什么?
【发布时间】:2019-05-10 07:15:45
【问题描述】:

最近我要连接到 PostgreSQL,我需要在我的对象中存储日期/时间以传递给查询以插入和更新某些表。 但是 C++ 中没有明确的方法来存储和检索日期/时间。 有什么意见吗?

【问题讨论】:

  • 您可以将它从纪元转换为毫秒。你可能想看看chrono命名空间
  • 数据库中存储的数据的精度是多少?如果是 +-1 秒,那么,time_twilll 会做。

标签: c++ postgresql date datetime time


【解决方案1】:

PostgreSQL TimeFormat 9+ 版本 https://www.postgresql.org/docs/9.1/datatype-datetime.html

这是 microsecond 精度的 8byte int(64 bit) 时间格式,没有时区的 UTC(从表格顶部开始)。

当您创建表时,您可以通过 PostgreSQL current_timestamp 为记录添加时间戳,或者以整数 64bit microsecond format 的形式插入表中。由于 PostgreSQL 有多种时间格式,你应该从表中决定任何你想要的格式

PostgreSQL 方法 CREATE、INSERT、RETRIEVE

"CREATE TABLE example_table(update_time_column TIMESTAMP DEFAULT CURRENT_TIMESTAMP)"

"INSERT INTO example_table(update_time_column) VALUES update_time_column=CURRENT_TIMESTAMP"

"SELECT (EXTRACT(epoch FROM update_time_column)*1000000) FROM example_table"

C++ 方法

auto/int64_t cppTime = get64bitMicrosecondFormat from some library`

类似于这个答案的东西:Getting an accurate execution time in C++ (micro seconds)

然后将你的对象/记录推送到 PostGRESQL,在微秒内检索时,调整精度/1000 for milliseconds 等。

请不要忘记同步 PostgreSQL 和 C++ 时间戳长度(例如,每边 8 字节 - 8 字节),否则,您的时间将受到任何一方的限制,您将失去精度/获得意外时间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-27
    • 2016-12-22
    • 2013-06-14
    • 2011-04-16
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    相关资源
    最近更新 更多