To save a date to localStorage in JavaScript, you can use the localStorage.setItem()
method. This method takes two arguments: the key you want to associate with the data, and the data itself.
Here's an example of saving a date to localStorage:
index.tsx77 chars3 lines
The new Date()
constructor creates a new Date object representing the current date and time. The setItem()
method then saves this object to localStorage with the key 'myDate'
.
To retrieve the saved date from localStorage, you can use the localStorage.getItem()
method:
index.tsx74 chars3 lines
This will log the date string to the console. Note that localStorage can only store strings, so when you retrieve the data with getItem()
, it will be returned as a string. If you want to use the date object again, you will need to parse the string back into a date object:
index.tsx115 chars4 lines
gistlibby LogSnag