gpt4 book ai didi

javascript - 如何在html脚本中插入当前日期

转载 作者:行者123 更新时间:2023-11-27 23:34:58 25 4
gpt4 key购买 nike

我有当前的脚本。 var date 2 需要自动抓取当前日期,然后进行计算。我尝试了很多事情都没有成功,请帮忙。

<script>

// Here are the two dates to compare
var date1 = '2015-09-08';
var date2 = '2015-12-13';

// First we split the values to arrays date1[0] is the year, [1] the month and [2] the day
date1 = date1.split('-');
date2 = date2.split('-');

// Now we convert the array to a Date object, which has several helpful methods
date1 = new Date(date1[0], date1[1], date1[2]);
date2 = new Date(date2[0], date2[1], date2[2]);

// We use the getTime() method and get the unixtime (in milliseconds, but we want seconds, therefore we divide it through 1000)
date1_unixtime = parseInt(date1.getTime() / 1000);
date2_unixtime = parseInt(date2.getTime() / 1000);

// This is the calculated difference in seconds
var timeDifference = date2_unixtime - date1_unixtime;

// in Hours
var timeDifferenceInHours = timeDifference / 60 / 60;

// in weeks :)
var timeDifferenceInWeeks = timeDifferenceInHours / 24/7;

document.write(Math.ceil(timeDifferenceInWeeks));
</script>

最佳答案

您可以使用 new Date() 获取当前日期。请引用片段。

<script>

// Here are the two dates to compare
var date1 = '2015-09-08';
var date2 = '2015-12-13';

// First we split the values to arrays date1[0] is the year, [1] the month and [2] the day
date1 = date1.split('-');
date2 = date2.split('-');

// Now we convert the array to a Date object, which has several helpful methods
date1 = new Date(date1[0], date1[1]-1, date1[2]);
date2 = new Date(date2[0], date2[1]-1, date2[2]);

// We use the getTime() method and get the unixtime (in milliseconds, but we want seconds, therefore we divide it through 1000)
date1_unixtime = parseInt(date1.getTime());
date2_unixtime = parseInt(date2.getTime());
date3_unixtime = parseInt((new Date()).getTime());

// This is the calculated difference in seconds
var timeDifference = date2_unixtime - date1_unixtime;

var timeDifferenceInWeeks1 = timeDifference / (1000*60*60*24*7);
var timeDifferenceInWeeks2 = (date3_unixtime - date2_unixtime) / (1000*60*60*24*7);

document.write(Math.ceil(timeDifferenceInWeeks1)+'--'+Math.ceil(timeDifferenceInWeeks2));
</script>

关于javascript - 如何在html脚本中插入当前日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34259709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com