Reputation: 4505
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.
Upvotes: 0
Views: 454
Reputation: 28974
It's a very simple procedure to add days to a date. Here's a simple snippet:
// 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)
I thought this whole thing was quite interesting, so I took the liberty to create the more advanced script that takes work hours, weekends and special dates (i.e. holidays) into consideration:
// 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));
Upvotes: 3