使用JavaScript的两个日期之间的周数 [英] Number of weeks between two dates using JavaScript

查看:118
本文介绍了使用JavaScript的两个日期之间的周数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JavaScript返回两个日期之间的周数。

I'm trying to return the number of weeks between two dates using JavaScript.

所以我有以下变量:

var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();

if(day < 10) { day= '0' + day; }
if(month < 10) { month = '0' + month; }

var dateToday = day + '/' + month + '/' + year;

var dateEndPlacement = '22/06/2014';

如果小于10,我还会将日期和月份的前缀加上0。不确定是否这是正确的方法......所以欢迎另外的想法。

I've also prefixed the days and months with 0 if they are less than 10. Not sure if this is the correct way to do this... so alternative ideas would be welcomed.

然后我将这两个日期传递给以下函数:

And then I pass these two dates to the following function:

function calculateWeeksBetween(date1, date2) {
    // The number of milliseconds in one week
    var ONE_WEEK = 1000 * 60 * 60 * 24 * 7;
    // Convert both dates to milliseconds
    var date1_ms = date1.getTime();
    var date2_ms = date2.getTime();
    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms);
    // Convert back to weeks and return hole weeks
    return Math.floor(difference_ms / ONE_WEEK);
}

然而我收到错误:

未捕获TypeError:对象04/04/2014没有方法'getTime'

任何想法我做错了什么?

Any ideas what I am doing wrong?

对于那些要求/要问的人,我正在调用这样的函数:

For those that are asking/gonna ask, I'm calling the function like this:

 calculateWeeksBetween(dateToday, dateEndPlacement);


推荐答案

我建议使用 moment.js 这类事情。

但是如果你想要纯粹的话这里的javascript就是这样的:

But if you want to do it in pure javascript here is how I would do it:

function weeksBetween(d1, d2) {
    return Math.round((d2 - d1) / (7 * 24 * 60 * 60 * 1000));
}

然后拨打电话

weeksBetween(new Date(), new Date(2014, 6, 22));

这篇关于使用JavaScript的两个日期之间的周数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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