如何在pgSQL中将日期作为整数获取

时间:2017-07-05 04:24:55

标签: php postgresql date stored-procedures

如何在pgsql中按月获取日期。我需要按日期的月份范围划分一个值。如 2016/01/31 2016/03/31 2个月期间,我需要将值除以2 即可。我发送两个日期作为pgSQL存储过程的参数。

1 个答案:

答案 0 :(得分:1)

这是按月份的功能日期周期返回整数

CREATE OR REPLACE FUNCTION date_period(start_date varchar,end_date varchar) RETURNS integer AS $LABEL$
DECLARE 
v_result integer;
BEGIN

select into v_result date_part('months',end_date::date)- date_part('months',start_date::date) as date_period;

/* v_result is integer */
RETURN (v_result);

/* COMMENTS THIS IF YOU IN DEBUG MODE */
EXCEPTION WHEN OTHERS THEN RETURN (999);

END;
$LABEL$ LANGUAGE plpgsql
SECURITY DEFINER;

EXEC:SELECT * FROM date_period('2016/01/31','2016/05/31');

不同年份,您可以使用此功能

CREATE OR REPLACE FUNCTION date_period(start_date varchar,end_date varchar) RETURNS integer AS $LABEL$
DECLARE 
v_result integer;
BEGIN

select into v_result ((extract( epoch from end_date::date)-extract( epoch from start_date::date))/60/60/24/30)::integer as date_period;

/* v_result is integer */
RETURN (v_result);

/* COMMENTS THIS IF YOU IN DEBUG MODE */
EXCEPTION WHEN OTHERS THEN RETURN (999);

END;
$LABEL$ LANGUAGE plpgsql
SECURITY DEFINER;

EXEC:SELECT * FROM date_period('2016/01/31','2017/03/31');