Tuesday, June 2, 2020

PostgreSQL: Get the TimeStamp of the beginning of a year, a month, or a day

To get the timestamp of the beginning of a year:

     //current year
      select date_trunc('YEAR', CURRENT_TIMESTAMP);

      //any year
      select date_trunc('YEAR', CURRENT_TIMESTAMP - INTERVAL '4 year');  or
      select date_trunc('YEAR', CURRENT_TIMESTAMP + INTERVAL '3 year'); or
      select TIMESTAMP '2019-01-01';

To get the timestamp of the beginning of a month:

      //current month
      select date_trunc('MONTH', CURRENT_TIMESTAMP);

      //any month
      select date_trunc('MONTH', CURRENT_TIMESTAMP - INTERVAL '9 month'); or
      date_trunc('MONTH', CURRENT_TIMESTAMP + INTERVAL '2 month'); or
      select TIMESTAMP '2019-08-01';

To get the timestamp of the beginning of a day:
   
      //current day
      select date_trunc('DAY', CURRENT_TIMESTAMP);

      //last day of the month
      select date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 month - 1 day';

      //last day of the month of a given date
      select date_trunc('MONTH', TIMESTAMP '2018-09-01) + INTERVAL '1 month - 1 day';

      //last day of the year
      select date_trunc('YEAR', CURRENT_DATE) + INTERVAL '1 year - 1 day';

      //last day of the year of a given date
      select date_trunc('YEAR', TIMESTAMP '2020-05-03') + INTERVAL '1 year - 1 day';

      //any day
      select date_trunc('DAY', CURRENT_TIMESTAMP - INTERVAL '12 day'); or
      select date_trunc('DAY', CURRENT_TIMESTAMP + INTERVAL '22 day'); or
      select TIMESTAMP '2019-08-25'; or
      select date_trunc('DAY', CURRENT_TIMESTAMP + INTERVAL '2 month + 5 day');
      select date_trunc('DAY', CURRENT_TIMESTAMP - INTERVAL '3 year - 2 month + 12 day');
   
Be aware when you minus an INTERVAL, the "- INTERVAL '3 year - 2 month - 12 day'" reduces three years from the current_timestamp, adds 2 months to it, and minuses twelve days from it.

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.

No comments:

Post a Comment