Home > Software design >  get specific date, from specific day last week
get specific date, from specific day last week

Time:08-20

Hi there guys i have an issue

i'm planning to get date from specific day from last week in node.js

for example if today is friday or any day, i want to know what date is sunday from the last week

i'm thinking to have this solution in using JS library or Postgresql.

my goal were to be able to query sunday last week to 13 weeks before that.

thank you for your time and efforts guys any solution were appreciated cheers!

CodePudding user response:

You can use this NPM Package for getting Dates

Moment.js 2.29.4 Parse, validate, manipulate, and display dates and times in JavaScript

https://momentjs.com/

Momentjs is most popular and powerful

// Last week
console.log(moment().subtract(7, 'days').calendar());
console.log(moment().subtract(7, 'days').calendar());
// formats
console.log(moment.locale());         // en
console.log(moment().format('LT'));   // 3:10 PM
console.log(moment().format('LTS'));  // 3:10:58 PM
console.log(moment().format('L'));    // 08/20/2022
console.log(moment().format('l'));    // 8/20/2022
console.log(moment().format('LL'));   // August 20, 2022
console.log(moment().format('ll'));   // Aug 20, 2022
console.log(moment().format('LLL'));  // August 20, 2022 3:10 PM
console.log(moment().format('lll'));  // Aug 20, 2022 3:10 PM
console.log(moment().format('LLLL')); // Saturday, August 20, 2022 3:10 PM
console.log(moment().format('llll')); // Sat, Aug 20, 2022 3:12 PM
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>  
<script src="https://momentjs.com/static/js/global.js"></script>
<script src="https://momentjs.com/static/js/core-home.js"></script>

CodePudding user response:

In advance: my PostgreSQL knowledge is very limited, so there might be better ways. Having said this, PostgreSQL provides a number of Date/Time Functions and Operators.

One can extract the current day of week (ISO numbering) using EXTRACT(ISODOW FROM CURRENT_DATE), which would return 6 if executed on a saturday, and 7 if executed on a sunday. Therefore you simply need to subtract the value from 7 to get the number of days to the next sunday. Add this value to the current date and you'll have the date of the upcoming sunday. From this you just need to subtract the desired interval, e. g.

SELECT CAST(
         CURRENT_DATE   CAST(7 - EXTRACT(ISODOW FROM CURRENT_DATE) AS integer) -
         MAKE_INTERVAL(weeks => 2) 
       AS DATE)

will return 2022-08-07 because it's the sunday two weeks before the upcoming sunday at 2022-08-21.

  • Related