从本地存储中保存和检索日期 [英] Saving and retrieving Date from local storage

查看:48
本文介绍了从本地存储中保存和检索日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);

如您所见,我正在生成今天的日期并通过本地存储将其存储.现在,我想在另一个函数中检索此值,将其添加7天,再次存储,然后在警报框中显示新值.

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);

当我运行这段代码时,它会不断告诉我 Undefined不是一个函数,它位于第二个代码块的第二条规则(可能是.getDate()函数).

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

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

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

推荐答案

放到localStorage中的所有内容都存储为字符串.您的约会日期原来是一个对象.从localStorage获取值后,需要将字符串转换回对象.

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);

这篇关于从本地存储中保存和检索日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆