将日期添加到日期是一个非常简单的过程。这是一个简单的片段:
// 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));