Postgres和部分日期

mal*_*ree 5 sql database postgresql nosql

所以我有一张桌子.该表中的每个条目都有一个与之关联的日期,其必须:

  • 支持部分日期:1994年2月5日,格林尼治标准时间16点45分+ 4 2003年4月都有效
  • 可比较:我想查询特定日期之前或之后的每个条目(此日期始终完成,即精确到秒和时区).2003年4月应该在1994年2月2日,格林威治标准时间16点45分+4之后,日期应该精确排序(即2003年4月*在2003年3月3日之前).

你会如何解决这个问题?我目前正在使用Postgres(但不依赖于它)并倾向于只int为每个日期属性都有一个列的方法,将实际的排序/比较逻辑转移到应用程序中.

任何有趣的想法?

sim*_*onp 7

您可以使用ISO 8601日期字符串.ISO日期格式支持您描述的表单的部分日期(但请注意不是例如"4月23日"而没有一年).

你的例子是:

  • "1994年2月5日,格林尼治标准时间16:45 + 4": 1994-05-02T12:45:00Z
  • "2003年4月": 2003-04

您可以将这些作为简单字符串进行排序和比较,并获得您想要的结果.即2003-04-03在词汇之后2003-04.

你可以从最后删除任何级别的精度,它仍然可以工作.您无法从开头或中间删除组件.

Note that you need to normalize all time-zones to UTC for this to work correctly, as in the above example.

An alternate approach, if you prefer to use date/timestamp types in the database, is to store the date's precision in a secondary column. E.g. store "April 2003" as a timestamp in the date field, and use a flag in a secondary field to indicate that this date is stored with "month" precision and should not be interpreted as being "1 April 2003, 12am".