商店日期与可选的月/日 [英] Store date with optional month / day

查看:143
本文介绍了商店日期与可选的月/日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Postgres数据库中存储日期。

唯一的问题是这个日期可以是可选的日子甚至月份。

I want to store date in my Postgres database.
The only problem is that this date can have optional day or even month.

示例:

用户提供受雇时间 - 不是必需的完整日期(日+月+年),但只能开始年份和结束年份。

但是有用户,谁也只能从同一年的10月份到这个月份才能提供。

Example:
User provides time period when he was employed - not necessary full date (day + month + year), but only start year and end year.
However there are users, who worked only from may to october in the same year so month have to be provided too.

如何处理这种可选的日期部分?

How to handle this kind of optional date parts?

推荐答案

使用正确的日期类型。不要 存储文本或多列。这将是更昂贵和更不可靠的。

Use a proper date type anyway. Do not store text or multiple columns. That would be more expensive and less reliable.

使用函数 to_date() ,这是适合您的需求开箱即用。例如,如果您使用模式'YYYYMMDD'调用它,并且实际字符串缺少日期或月份和日期的字符,则默认为第一个月/年/月:

Use the function to_date(), which is fit to deal with your requirements out of the box. For instance, if you call it with a pattern 'YYYYMMDD' and the actual string is missing characters for day, or month and day, it defaults to the first month / day of the year / month:

db=# SELECT to_date('2001', 'YYYYMMDD');
  to_date
------------
 2001-01-01

db=# SELECT to_date('200103', 'YYYYMMDD');
  to_date
------------
 2001-03-01

如果需要,您可以存储指示年/月/日的精确标志。

You could store a precision flag indicating year / month / day in addition if you need that.

这篇关于商店日期与可选的月/日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆