0

I am wondering what the best way of doing this is. I am trying to have an estimated delivery time script where in the html on the page I have: 2

the 2 number will change per page but this will be the ammount of days delivery takes, now I would like another div's contents to show [ammount] of days from the date today: Friday 26th

getting the div's etc will be easy however I have no idea what kind of function I could use to get a date countdown. Any help greatly appreciated, Thanks.

4

1 回答 1

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));
于 2013-07-24T13:59:31.673 回答