PostgreSQLextract根据 ISO 8601 标准提供了获取日期年份和周数的函数,该标准每年的第一周包含 1 月 4 日。
这些可以提取如下(使用今天作为日期):
select extract(isoyear from current_date);
select extract(week from current_date);
Run Code Online (Sandbox Code Playgroud)
但这个函数似乎没有逆函数。我正在寻找一种方法来获取 ISO 8601 年和周中的第一个日期。有任何想法吗?
小智 5
to_date()支持 ISO 年和 ISO 周。
因此,您首先需要获取“年初”(使用date_trunc()),然后将其转换为正确的“周”(使用to_char())并将其转换回日期(使用to_date()):
to_date(to_char(date_trunc('year', current_date), 'iyyy-iw'), 'iyyy-iw')
Run Code Online (Sandbox Code Playgroud)
这个说法:
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');
Run Code Online (Sandbox Code Playgroud)
在 2015 年 12 月 7 日运行时,将返回:
date_trunc | to_char | to_date
--------------------+---------+-----------
2015-01-01 00:00:00 | 2015-01 | 2014-12-29
Run Code Online (Sandbox Code Playgroud)