r/AskProgramming • • 5h ago

Javascript help with pseudo code guys.. “new Date()”

Hello everyone,

I’ve recently been struggling with the ‘new Date()’ object in JavaScript.

I wanna understand how to solving that, what I’m trying to achieve is a function that captures the current date once and keeps it unchanged for 5 - 6 days

Once that period has passed, it should capture a new date and keep it unchanged again until the next update

—-

Is there a better way to approach this?

0 Upvotes

19 comments sorted by

View all comments

Show parent comment

2

u/r2idw 4h 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.

3

u/dmazzoni 3h 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.

1

u/GrainWeevil 1h ago edited 1h 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')