如何计算和检查每两周一次的日期

时间:2016-12-19 21:01:36

标签: javascript date recurrence

我真的需要你的帮助,

假设我的分界开始日期是:2016年12月19日,由变量x定义

如何编写JavaScript函数,以便它将根据x和当前日期检查当前日期,以确定重复日期距离x的重复日期(14)变量y

var y = recurrence is every 14 days, thereafter from the date (x) with no end date specified (unlimited)

实施例

function() {

    if (present date == x) { alert(true) }

    if (present date == y) { alert(true) }

}

4 个答案:

答案 0 :(得分:2)

您可以获得开始日期和当前日期之间的天数差异,然后检查该数字是否是14的倍数。

function treatAsUTC(date) {
    var result = new Date(date);
    result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
    return result;
}

function daysBetween(startDate, endDate) {
    var millisecondsPerDay = 24 * 60 * 60 * 1000;
    return Math.floor((treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay);
}

var demarcationdate = new Date("2016-12-19"), 
    today = new Date(),
    days = daysBetween(demarcationdate,today),
    daystill = 14 - days%14,
    rec = days%14==0,
    d = new Date();

d.setDate(today.getDate() + daystill);
var nextDate = (d.getDate() + "/" + (d.getMonth() + 1) + "/" + d.getFullYear());

console.log("Days diff = "+days+". Recurs today = "+rec+". Next in "+daystill+" days ("+nextDate.toString()+").");

jsFiddle

答案 1 :(得分:0)

如果Date.now() == 1482181410856,则从现在开始的14天将是1482181410856 + (14 * 24 * 60 * 60 * 1000) == 1483391010856

let y = new Date(Date.now() + (14 * 24 * 60 * 60 * 1000));
console.log(y.toUTCString()); // "Mon, 02 Jan 2017 21:03:30 GMT"

答案 2 :(得分:0)

假设你真的想比较精确的日期,即毫秒,那么:

var present_date = new Date();
if(present_date.getTime() === x.getTime()) alert("Today is the same date as x");
else {
    var y = new Date(x.getTime());
    y.setDate(y.getDate() + 14); // add 14 days
    if(present_date.getTime() === y.getTime()) alert("Today is the same date as y");
}

但是大部分时间我们都希望将日期比较为整天,而不是毫秒,所以你必须比较范围(从午夜到晚上11:59)...在这种情况下,我建议使用库来让您的生活更轻松 - 例如moment.js ......

希望这有帮助!

答案 3 :(得分:0)

这可能是Add +1 to current date的副本。

如果您有开始日期,例如2016年12月20日,您可以在此之后的14天内计算,只需在该日期添加14天即可。然后,您可以检查今天的日期是否为这些日期之一,例如



// Create a Date for 20 December, 2016 with time 00:00:00
var startDate = new Date(2016,11,20);

// Create a Date for the start + 14 days with time 00:00:00
var startPlus14 = new Date(startDate);
startPlus14.setDate(startPlus14.getDate() + 14);

// Get today and set the time to 00:00:00.000
var today = new Date();
today.setHours(0,0,0,0);

if (+today == +startDate) {
  console.log('Today is the start date');
} else if (+today == +startPlus14) {
  console.log('Today is 14 days after the start date');
} else {
  console.log('Today is neither the start nor 14 days after the start');
}