r/AskProgramming • • 2d ago

Javascript [ Removed by moderator ]

[removed] — view removed post

0 Upvotes

21 comments sorted by

View all comments

Show parent comment

2

u/r2idw 2d ago

The script is running in the browser, and the specific problem I’m facing is with a calendar that consists of 7 days

Let’s say I extract 7 days from a Date object by doing something like today, today + 1, today + 2, and so on until I get all 7 days

The problem is that the dates inside the calendar keep updating daily. Imagine I initially have Dec 2 to Dec 8. When tomorrow comes, it changes to Dec 3 to Dec 9

What I actually want is to keep those original 7 days in the calendar without changing them daily. Once the 7-day period is over, I’ll grab another 7 days using the current date and repeat the same process.

2

u/GrainWeevil 2d ago edited 2d ago

Got it, sounds like local storage is what you're looking for.

Essentially, when you start your application, you'd check if there's a date stored in local storage. If there is, check if a week has passed since that date, and update it if so.

Have a read of this: https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API

You'll probably need to format the date as a string before trying to save it, but writing to local storage is as easy as:

localStorage.setItem('savedDate', dateString)

And reading it back:

let dateString = localStorage.getItem('savedDate')

2

u/dmazzoni 2d ago

Are you reloading the web page every day?

If so, every time you do that it restarts your program from scratch.

Your problem isn’t with Date(), it’s with saving stuff between runs.

Learn localStorage.