获取今天JQuery的天数

时间:2013-07-24 13:52:09

标签: javascript jquery

我想知道这样做的最佳方法是什么。我想在页面上的html中有一个估计的交付时间脚本:2

2号码将在每页更改,但这将是几天的交付时间,现在我希望另一个div的内容显示从今天开始[ammount]天数:星期五26日

得到div的等等很容易,但是我不知道我可以使用什么样的功能来获得日期倒计时。非常感谢任何帮助,谢谢。

1 个答案:

答案 0 :(得分:3)

将日期添加到日期是一个非常简单的过程。这是一个简单的片段:

// Get the current date
var now = new Date();
// Add three days
now.setDate(now.getDate() + 3);
// Log the updated Date object to the console
console.log(now); //= Sat Jul 27 2013 16:00:00 GMT+0200 (W. Europe Daylight Time)

我认为这一切都非常有趣,所以我冒昧地创建了更高级的脚本,将工作时间,周末和特殊日期(即假期)考虑在内:

// Current date/time
var now = new Date();
// Placeholder for delivery time
var deliveryDate;
// Amount of days to deliver
var deliveryDays = 2;
// Working hours (in UTC)
var workingHours = [8, 17];

// Non-delivery days/dates
// Must match the format returned by .toString(): 
// Mon Sep 28 1998 14:36:22 GMT-0700 (Pacific Daylight Time)
var nonDelivery = [
    "Sun",
    "Sat",
    "Dec 24",
    "Dec 25",
    "Dec 31",
    "Jan 1"
];

// Create a regular expression
var rxp = new RegExp(nonDelivery.join("|"));

// addDay holds the amount of days to add to delivery date
var addDay = deliveryDays;

// Add an extra day if outside of working hours
var currentHour = now.getUTCHours();
if (currentHour < workingHours[0] || 
    currentHour > workingHours[1]) {
    addDay++;
}

// Let's create our delivery date
while (!deliveryDate) {
    // Add day(s) to delivery date
    now.setDate(
        now.getDate() + addDay
    );
    deliveryDate = now;
    if (rxp.test(deliveryDate)) {
        addDay = 1;
        deliveryDate = false;
    }
}

// Function to get ordinal
function nth(d) {
  if (d > 3 && d < 21) return 'th';
  switch (d % 10) {
        case 1:  return "st";
        case 2:  return "nd";
        case 3:  return "rd";
        default: return "th";
    }
} 

// Now lets format
var locale = "en-GB"; // Our locale
var day = deliveryDate.toLocaleDateString(locale, { day: "numeric" });
var weekday = deliveryDate.toLocaleDateString(locale, { weekday: "long" });

// Log the results to the console
console.log(weekday + " " + day + nth(day));