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

标签 javascript html

我有当前的脚本。 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/

相关文章:

javascript - 使用 javascript/css 的气泡爆炸动画

CSS 嵌套列表到多列

javascript - 传播语法的替代方案

javascript - 如何使用 JavaScript 知道一个国家是否正在使用夏令时?

javascript - JQuery "greying"在表单中输出文本字段

javascript - 如何在单元格5之后动态添加行vue.js

c# - 实现应用程序 HTML 帮助系统

javascript - 从客户端隐藏 loggly 输入 token

javascript - 如何使用 AJAX 数据传递 url GET 值

javascript - 算法:如何划分网格列宽(如google-chrome)