我在下个月的随机日期创建随机时间,就像这样
var time = new Date(now.getFullYear(),
now.getMonth() + 1,
Math.floor(Math.random()*28),
Math.floor(Math.random()*25),
Math.floor(Math.random()*60),
Math.floor(Math.random()*60),
Math.floor(Math.random()*1000)
);
我想将此日期保存为字符串,然后将其转换回日期
我用
var time_for_save = time.toUTCString();
这给了我这样的字符串:
Sat, 01 Oct 2011 07:42:38 GMT
如何将此日期转换回Date对象?
或者有没有更好的方法来通过字符串保存/检索Date对象?
答案 0 :(得分:4)
给定日期字符串表示,您可以使用Date.parse函数获取'日期字符串与1970年1月1日午夜之间的毫秒数。';之后,您可以使用日期构造函数从'epoch毫秒'获取新的日期对象。
var date = new Date(Date.parse(time_for_save));
答案 1 :(得分:1)
Date
构造函数接受一个字符串:
var restoredDate = new Date(time_for_save);