Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving and retrieving Date from local storage

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...

like image 850
Programmer1994 Avatar asked Apr 14 '15 14:04

Programmer1994


People also ask

Is it safe to save data in local storage?

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.

How can I save my local data?

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.

How long local storage keeps data?

LocalStorage has no expiration time, Data in the LocalStorage persist till the user manually delete it.


2 Answers

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);
like image 82
Lloyd Banks Avatar answered Oct 12 '22 22:10

Lloyd Banks


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);
like image 28
taxicala Avatar answered Oct 12 '22 22:10

taxicala