typescript 从本地存储保存和检索日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29629458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:59:13  来源:igfitidea点击:

Saving and retrieving Date from local storage

javascripttypescriptlocal-storage

提问by Programmer1994

This may seem like a silly question but I'm having a rather difficult time, understanding Typescript. I have following code:

这似乎是一个愚蠢的问题,但我很难理解 Typescript。我有以下代码:

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.

如您所见,我正在生成今天的日期并通过本地存储进行存储。现在我想在另一个函数中检索这个值,向它添加 7 天,再次存储它,并在警报框中显示新值。

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 functionon the second rule of the second code-block (probably the .getDate() function).

当我运行这段代码时,它不断告诉我Undefined is not a function第二个代码块的第二条规则(可能是 .getDate() 函数)。

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

有人知道我可能做错了什么吗?我认为这段简单的 javascript 可以在打字稿中正常运行而无需更改代码...

回答by Lloyd Banks

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.

放入 localStorage 的所有内容都存储为字符串。您的日期最初是一个对象。从 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);

回答by taxicala

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:

您应该将时间戳存储在 localStorage 中,然后检索它,使用该时间戳创建一个新的 Date,添加 7 天,然后再次存储它:

var date1 = new Date();
window.localStorage.setItem("date", date.getTime());

var date2 = new Date(window.localStorage.getItem("date"));
date2.setDate(date2.getDate() + 7);
window.localStorage.setItem("date", date2.getTime());
alert(date2);

回答by Nathan Merrill

If you perform the following

如果您执行以下操作

var date = new Date();
window.localStorage.setItem("date", date);
var date1 = window.localStorage.getItem("date");
console.log(date1)

You will find that date1is a string. This is because localStorage stores all of its data as strings.

你会发现那date1是一个字符串。这是因为 localStorage 将其所有数据存储为字符串。

You should parse the string by creating a new Date with the returned string.

您应该通过使用返回的字符串创建一个新的 Date 来解析字符串。