time.Since() with months and years

前端 未结 5 1664
悲哀的现实
悲哀的现实 2020-12-01 11:20

I am trying to convert a timestamp like this:

2015-06-27T09:34:22+00:00

to a time since format so it would say like 9 months ago 1 day 2 ho

5条回答
  •  时光取名叫无心
    2020-12-01 11:42

    If you use PostgreSQL, you can easily get the result with age function.

    Suppose you have two dates a and b.

    Like icza said, be careful, a and b must be in the same time zone.

    First, you can invoke age with two parameters, in your case date a and date b. This function return a interval type that contains years, months, weeks, days, hours, minutes, seconds, and milliseconds.

    SELECT age('2016-03-31', '2016-06-30'); -- result is: -2 mons -30 days
    

    The second possibilty is to use age function with one parameter. The result is a interval too but in this case, age subtract from current_date (at midnight). Suppose today is 2016/06/16:

    SELECT age(timestamp '2016-06-30'); -- result is: -14 days
    

    Note, timestamp keyword is needed to cast the date '2016-06-30'.

    For more details, you can use date_part or directly extract function that return one specific field (years, months, days...).

    SELECT date_part('month', age('2016-03-31', '2016-06-30')); --result is: -2
    SELECT date_part('day',   age('2016-03-31', '2016-06-30')); --result is: -30
    

    Full request:

    SELECT  
        date_part('year', diff) as year
      , date_part('month', diff) as month
      , date_part('day', diff) as day
    FROM (
      SELECT age(timestamp '2016-06-30') AS diff
    ) as qdiff;
    
    -- result is: 
    -- year month day
    -- 0    0     -14
    

    (with CTE - Common Table Expression):

    WITH qdiff AS (
      SELECT age(timestamp '2016-06-30') AS diff
    )
    SELECT  
        date_part('year', diff) as year
      , date_part('month', diff) as month
      , date_part('day', diff) as day
    FROM qdiff
    
    -- result is: 
    -- year month day
    -- 0    0     -14
    

    PostgreSQL documentation (current version): https://www.postgresql.org/docs/current/static/functions-datetime.html

提交回复
热议问题