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.
5
Answers
After research and trying I find this way will be the best way, by using moment.js:
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
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.will return 2022-08-07 because it’s the sunday two weeks before the upcoming sunday at 2022-08-21.
Here is the exact solution that you are looking for in vanilla JS.
To find the Sunday of the previous week and "n" weeks before that:
Postgres simple direct date manipulation routines: What you asking is accomplished by interval subtraction and the date_trunc() function. For your example of 2022-08-20 I assume you want 2022-08-07 (Sunday of the prior week). So
How it works:
above
interval
calculations generate timestamps results.As far as getting start of week for several weeks back wrap the above in a SQL function with the number of desired weeks as a parameter and multiple the
- '1 week'
by that value. (See demo)