日期来自toUTCString()

date from toUTCString()

本文关键字:toUTCString 日期      更新时间:2023-09-26

我将在下个月的随机日期创建随机时间,像这样

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。解析函数获取'日期字符串与1970年1月1日午夜之间的毫秒数';之后,您可以使用日期构造函数从'epoch milliseconds'中获取一个新的日期对象。

var date = new Date(Date.parse(time_for_save));

Date构造函数接受字符串:

var restoredDate = new Date(time_for_save);