This may seem like a silly question but I'm having a rather difficult time, understanding Typescript. I have following code:
var date = new Date();
window.localStorage.setItem("date", date);
As you see, I'm generating todays date and store it via local storage. Now I want to retrieve this value inside another function, add 7 days to it, store it again, and show the new value in an alert-box.
var date = window.localStorage.getItem("date");
date.setDate(date.getDate() + 7);
window.localStorage.setItem("date", date);
alert(date);
When I run this code, it keeps telling me Undefined is not a function
on the second rule of the second code-block (probably the .getDate() function).
Someone who knows what I might be doing wrong? I thought this simple piece of javascript would run fine in typescript without changing the code...
On the downside, localStorage is potentially vulnerable to cross-site scripting (XSS) attacks. If an attacker can inject malicious JavaScript into a webpage, they can steal an access token in localStorage. Also, unlike cookies, localStorage doesn't provide secure attributes that you can set to block attacks.
Any content/data saved to the localStorage object will be available after the browser has been restarted (closed and opened again). In order to save an item to localStorage , you can use the method setItem() . This method must be handed a key and a value.
LocalStorage has no expiration time, Data in the LocalStorage persist till the user manually delete it.
Everything put into localStorage is stored as a string. Your date is originally an object. You need to convert the string back to an object after you get the value from localStorage.
var date = window.localStorage.getItem("date");
// Initialize the date object as a date object again here
date = new Date(date);
date.setDate(date.getDate() + 7);
You should store the timestamp in localStorage, and then retreive it, create a new Date with that timestamp, add 7 days, and then store it again:
var date1 = new Date();
window.localStorage.setItem("date", date1.getTime());
var date2 = new Date(Number(window.localStorage.getItem("date")));
date2.setDate(date2.getDate() + 7);
window.localStorage.setItem("date", date2.getTime());
alert(date2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With