获得ISO 8601年和周的第一个日期

时间:2015-12-07 11:48:36

标签: postgresql

PostgreSQL提供extract功能,根据ISO 8601标准获取日期的年份和周数,该标准包含每年的第一周,包含1月4日。

这些可以如下提取(使用今天作为日期):

select extract(isoyear from current_date);
select extract(week from current_date);

但似乎没有这个函数的反转。我正在寻找的是一种在ISO 8601年和一周内获得第一次约会的方法。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

to_date()支持ISO年份和ISO周。

所以你首先需要获得“年初”(使用date_trunc()),然后将其转换为正确的“周”(使用to_char())并将其转换回日期(使用to_date()):

to_date(to_char(date_trunc('year', current_date), 'iyyy-iw'), 'iyyy-iw')

本声明:

select date_trunc('year', current_date), 
       to_char(date_trunc('year', current_date), 'iyyy-iw'),
       to_date(to_char(date_trunc('year', current_date), 'iyyy-iw'), 'iyyy-iw');

在2015-12-07运行时返回:

date_trunc          | to_char | to_date   
--------------------+---------+-----------
2015-01-01 00:00:00 | 2015-01 | 2014-12-29
相关问题