Shopify estimated delivery - javascript

I am looking to show an estimated delivery date on the product page for each delivery option we have. I have read through the code in Shopify Variants by Steph Sharp which would work brilliantly except we would need it to be fixed to the current day up until 3pm and then switch to the next working day after 3pm. (Basically taking away the option for the customer to choose the dispatch day.)
I can’t quite get it to work by butchering this code into our template. This is what I have butchered together which seems to work okay but rather than have MON, TUE, WED, … I want to set them as the future dates. Any advice?
EDIT: Also I heard Palec is after using a timer code with this code too. So I will add that in.
<script language="JavaScript">
function day(a) {
var date = new Date();
var days = ["Mon","Tue","Wed","Thur","Fri","Mon","Tue","Wed","Thur","Fri","Mon","Tue","Wed","Thur","Fri"];
var today = date.getDay();
if (today == 1) today = 0; //Monday
if (today == 2) today = 1; //Tuesday
if (today == 3) today = 2; //Wednesday
if (today == 4) today = 4; //Thursday
if (today == 5) today = 5; //Friday
if (today == 6) today = -1; //Saturday Moved To Monday
if (today == 0) today = -1; //Sunday Moved To Monday
h = date.getHours();
if (h <= 9) h = "0" + h;
time = h;
if (time > 15) today++;
var expected = today + a;
var main = days[expected];
document.write('STANDARD DELIVERY ESTIMATE: ');
document.write(main);
}
</script>
<body>
<script language="JavaScript">
day(1)
</script>

I would try something like this:
function day(a) {
var date = new Date();
var hours = date.getHours();
// If after 3pm, add 1 day
if(hours > 15) a++;
var expectedDeliveryDate = addWeekdays(date, a);
document.write(expectedDeliveryDate.toDateString() + ' with Standard Delivery');
}
function addWeekdays(fromDate, days) {
var count = 0;
while (count < days) {
fromDate.setDate(fromDate.getDate() + 1);
if (fromDate.getDay() != 0 && fromDate.getDay() != 6) // Skip weekends
count++;
}
return fromDate;
}
(The code in the addWeekdays function is from this answer on Stack Overflow.)
This code just displays the day name (like the code in your question), but you can format expectedDeliveryDate however you want.
EDIT: I updated my code to use expectedDeliveryDate.toDateString() as specified in the comments. Note that you no longer need the days array or expectedDeliveryDay variable. (You've still got them in your answer but they're not being used.)

This is my final code, based on Steph Sharp’s answer.
function day(a) {
var date = new Date();
var hours = date.getHours();
// If after 3pm, add 1 day
if (hours >= 15) a++;
var expectedDeliveryDate = addWeekdays(date, a);
document.write(expectedDeliveryDate.toDateString() + ' with Standard Delivery');
}
function addWeekdays(fromDate, days) {
var count = 0;
while (count < days) {
fromDate.setDate(fromDate.getDate() + 1);
if (fromDate.getDay() != 0 && fromDate.getDay() != 6) // Skip weekends
count++;
}
return fromDate;
}
Also added a timer:
function ShowTime() {
var now = new Date();
var hrs = 15 - now.getHours();
if (hrs < 0) hrs += 24;
var mins = 60 - now.getMinutes();
var secs = 60 - now.getSeconds();
timeLeft = "" + hrs + ' hours ' + mins + ' minutes ' + secs + ' seconds';
$("#countdown").html(timeLeft);
}
var countdown = setInterval(ShowTime, 1000);
function StopTime() {
clearInterval(countdown);
}

Related

Javascript Countdown to show/hide on specified days & hours

Hi I've been trying to take and work with some code that I can get partially working, I want a countdown that we can set an end time it counts down to (obvious is obvious out of the way), we also want to set it to show at only certain times of the day and only certain days of the week.
I've managed to get the below working so we can set a time of the day to show but I can't get it to work so it only shows on the certain specified days. Can anyone help please?
var countdownMessage = "This ends in";
var now = new Date();
var time = now.getTime(); // time now in milliseconds
var countdownEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12, 59); // countdownEnd 0000 hrs
//////////////////////////* Countdown *///////////////////////////////
function getSeconds() {
var ft = countdownEnd.getTime() + 86400000; // add one day
var diff = ft - time;
diff = parseInt(diff / 1000);
if (diff > 86400) {
diff = diff - 86400
}
startTimer(diff);
}
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval("tick()", 1000);
tick(); // to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
} else {
clearInterval(ticker); // stop counting at zero
//getSeconds(); // and start again if required
}
var hours = Math.floor(secs / 3600);
secs %= 3600;
var mins = Math.floor(secs / 60);
secs %= 60;
var result = ((hours < 10) ? "0" : "") + hours + " hours " + ((mins < 10) ? "0" : "") + mins + " minutes " + ((secs < 10) ? "0" : "") + secs + " seconds";
document.getElementById("countdown").innerHTML = (countdownMessage) + " " + result;
}
///////////////* Display at certain time of the day *//////////////////
//gets the current time.
var d = new Date();
if (d.getHours() >= 7 && d.getHours() <= 15) {
$("#countdown").show();
} else {
$("#countdown").hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body onload="getSeconds()">
<span id="countdown" style="font-weight: bold;"></span>
</body>
[EDIT]
Just to add to this I tried changing part of the script to this but it didn't work:
$(function() {
$("#countdown").datepicker(
{ beforeShowDay: function(day) {
var day = day.getDay();
if (day == 1 || day == 2) {
//gets the current time.
var d = new Date();
if(d.getHours() >= 7 && d.getHours() <= 10 ){
$("#countdown").show();
}
else {
$("#countdown").hide();
}
} else {
$("#countdown").hide();
}
}
});
});
Whatever you did is all good except the setInterval part where you are passing the string value as setInterval("tick()", 1000) instead of a function reference as setInterval(tick, 1000)
Also, I have updated the code as below to check the specific day along with specific hours which you had,
var d = new Date();
var day = d.getDay();
if (day == 0 || day == 6) {
if (d.getHours() >= 0 && d.getHours() <= 8) {
$("#countdown").show();
} else {
$("#countdown").hide();
}
}
You can give a try below,
var countdownMessage = "This ends in";
var now = new Date();
var time = now.getTime(); // time now in milliseconds
var countdownEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12, 59); // countdownEnd 0000 hrs
//////////////////////////* Countdown *///////////////////////////////
function getSeconds() {
var ft = countdownEnd.getTime() + 86400000; // add one day
var diff = ft - time;
diff = parseInt(diff / 1000);
if (diff > 86400) {
diff = diff - 86400
}
startTimer(diff);
}
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval(tick, 1000);
tick(); // to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
} else {
clearInterval(ticker); // stop counting at zero
//getSeconds(); // and start again if required
}
var hours = Math.floor(secs / 3600);
secs %= 3600;
var mins = Math.floor(secs / 60);
secs %= 60;
var result = ((hours < 10) ? "0" : "") + hours + " hours " + ((mins < 10) ? "0" : "") + mins + " minutes " + ((secs < 10) ? "0" : "") + secs + " seconds";
document.getElementById("countdown").innerHTML = (countdownMessage) + " " + result;
}
$("#countdown").hide();
///////////////* Display at certain time of the day *//////////////////
//gets the current time.
var d = new Date();
var day = d.getDay();
if (day == 0 || day == 6) {
if (d.getHours() >= 0 && d.getHours() <= 8) {
$("#countdown").show();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body onload="getSeconds()">
<span id="countdown" style="font-weight: bold;"></span>
</body>

Javascript check if the time is between 8:30am and 6:30pm

Ok so what the title says. I am doing this on a server, so I get the server's time using some PHP code. The problem is that it is a time frame without exact round hour values. Should I use nested if else statements?
var serverTimestampMillis = <?php print time() * 1000 ?>;
var checkInterval = 1000;
var checkTime = function () {
serverTimestampMillis += checkInterval;
var now = new Date(serverTimestampMillis);
var timeDiv = document.getElementById('timeDiv');
var messageDiv = document.getElementById('messageDiv');
timeDiv.innerHTML = now.toString();
var dayOfWeek = now.getDay(); // 0 = Sunday, 1 = Monday, ... 6 = Saturday
var hour = now.getHours(); // 0 = 12am, 1 = 1am, ... 18 = 6pm
var minutes = now.getMinutes();
// check if it's Monday to Thursday between 8:30am and 6:30pm
// this is where I don't know how to check 8:30
if (dayOfWeek > 0 && dayOfWeek < 5 && hour > 8 && hour < 18) {
messageDiv.innerHTML = 'Yes, we are open!';
messageDiv.className='open';
}
else {
messageDiv.innerHTML = 'Sorry, we\'re closed!';
messageDiv.className='closed';
}
};
// check the time every 1000 milliseconds
setInterval(checkTime, checkInterval);
checkTime();
thank you in advance, and sorry for being a noob
Compare between two dates using a helper function:
function createDateTime(time) {
var splitted = time.split(':');
if (splitted.length != 2) return undefined;
var date = new Date();
date.setHours(parseInt(splitted[0], 10));
date.setMinutes(parseInt(splitted[1], 10));
date.setSeconds(0);
return date;
}
var startDate = createDateTime("8:30");
var endDate = createDateTime("17:30");
var now = new Date();
var isBetween = startDate <= now && now <= endDate;
console.log(isBetween);
JSFIDDLE.
You can just nest your statements, like you said (to make it easier to read), and then check the specific edge cases (8:30-9 and 18:00-18:30).
if (dayOfWeek > 0 && dayOfWeek < 5) {
if ((hour > 8 && hour < 18) ||
(hour == 8 && minutes >= 30) ||
(hour == 18 && minutes <= 30)) {
messageDiv.innerHTML = 'Yes, we are open!';
messageDiv.className='open';
}
}

javascript shipping countdown fails if i use a target of 14:30

I use the following javascript to show a countdown timer for shipping that day
var timerRunning = setInterval(
function countDown() {
var target = 14; // This is the cut-off point
var now = new Date();
//Put this in a variable for convenience
var weekday = now.getDay();
var despatchday = 'TODAY!';
if (weekday == 0) { //Sunday? Add 24hrs
target += 24;
despatchday = 'on Monday';
} //keep this before the saturday, trust me :>
if (weekday == 6) { //It's Saturday? Add 48hrs
target += 48;
despatchday = 'on Monday';
}
if ((weekday == 5) && (now.getHours() > target) && (now.getHours() <= 24)) {
target += 72;
despatchday = 'on Monday';
}
//If between Monday and Friday,
//check if we're past the target hours,
//and if we are, abort.
if ((weekday >= 1) && (weekday <= 5)) {
if ((now.getHours() > target) && (now.getHours() <= 24)) { //stop the clock
target += 24;
despatchday = 'tomorrow';
} else if (now.getHours() > target) { //stop the clock
return 0;
despatchday = 'today';
}
}
var hrs = (target) - now.getHours();
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = 'Order in the next ' + hrs + 'hrs ' + mins + 'mins ' + secs + 'secs for despatch ' + despatchday;
document.getElementById('countdownTimer').innerHTML = str;
}, 1000
);
The problem I have is that if I set the cut off time to anything other than a full hour the timer does not work.
The correct output is Order in the next xx hrs, xx mins xx secs for despatch today
If I set
var target = 14; // This is the cut-off point
as 14:30 it gives "Just checking the time"
I assumed that it needed the mins as a decimal but if I set it as 14.5 it is adding 0.5 hrs to the output; ie 23.5hrs 50mins 30secs
I have set up a fiddle here. http://jsfiddle.net/4eu4o6k0/
Ideally I need it to be able to handle time in the format of hh:mm as that is the format of the time stored in the database. Is there a correct way to process partial hours in this type of script?
you need to hand the decimal place of hrs:
var rem =hrs%1;
mins = mins + (rem*60);
hrs = hrs - rem;
if (mins > 59) {
mins = mins - 60;
hrs= hrs +1;
}
Also I think you meant to spell dispatch
I'd personally advise against writing own code for handling time intervals because it's known to be error-prone. Use moment.js or date.js for such things
Here's sample for Moment.js

Using boolean logic on time (javascript)

Javascript has built-in function for time where
var date = new Date();
d.getHours() //gets the hour in integer 0-23
d.getMinutes() //gets the minute in integer 0-59
I would like function (e.g. A()) to run between 0:35 and 4:35
Is this possible to do using just simple logic operation (&&, ||)?
I don't think it is possible, but I wanted to know the elegant way to implement it.
You could use the timestamp to compare.
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
var start = new Date(year, month, day, 0, 35);
var end = new Date(year, month, day, 4, 35);
if (date.getTime() >= start.getTime() && date.getTime() <= end.getTime()) {
//...
}
var date = Date.now(); // ES5 - or new Date().getTime()
var sec = (date / 1000); // seconds since epoch
sec = sec % 86400; // seconds since midnight
var mins = sec / 60; // minutes since midnight
if (mins >= 35 && mins < 4*60+35) {
A();
}
Technically it's possible, but you are absolutely right in that this is not an elegant solution:
var h = d.getHours();
var m = d.getMinutes();
if ((h == 0 && m >= 35) || (h > 0 && h < 4) || (h == 4 && m <=35)) {
A();
}
This should work:
function foo(){
var now = new Date();
if( (now.getHours() < 1 && now.getMinutes() < 35)
|| (now.getHours() > 3 && now.getMinutes() > 35) ){
return false; //if it isn't in your time, return false
}
//put your code here. this will run between the hours of 12:35AM and 4:35AM local time
}
I hope this is what you are looking for. If not, let me know.

adding time using javascript

I want to adding a time with current time using javascript....
Easiest to set an example...
e.g.
In the admin section set the "Minimum Hours Booking Notice" as 12 hours ($minHours = 12)
The time now is 10:30 on 26th July 2011
I want to book a vehicle for today at 17:00
BUT 10:30 + $minHours < 17:00
THEREFORE I CANNOT make the booking. Then I should be notified by a popup/ notice onscreen and the booking should not be allowed.
PHP Code for this.....
$hour1 = $this->input->post('time1');
$sec1 = $this->input->post('sec1');
$act = $hour1 . ':' . $sec1;
$min_hr = $this->input->post('min_hr');
$current_time = date("H:i");
$new_date = date('d');
$exe = explode(':', $current_time);
$new_time = $exe['0'] + $min_hr;
if ($new_time > 24) {
$new_time = $new_time - 24;
$new_date = date('d') + 1;
} else {
$new_time = $new_time;
$new_date = date('d');
}
if($date1 > $new_date){
if($hour1 > $new_time){
redirect('mesage');
} elseif ($hour1 == $new_time) {
if($sec1 <= $exe['1']){
redirect('mesage');
}
}
} elseif ($date1 == $new_date) {
if($hour1 < $new_time){
redirect('mesage');
} elseif ($hour1 == $new_time) {
if($sec1 <= $exe['1']){
redirect('mesage');
}
}
}
Please help....
a LOT of issues with your code. I am posting an answer for formatting and to understand the code
This is not needed
} else {
$new_time = $new_time;
$new_date = date('d');
}
what is date1?
Why do you have sec1 when you obviously mean minutes
Where will the parameters for the script come from?
Here is your php in JS
var hour1 = qs('time1'); // qs is some function that for example uses the query string
var min1 = qs('sec1'); // you do mean minutes, no?
var act = hour1 + ':' + min1;
var min_hr = qs('min_hr');
var new_date = new Date();
var hh = new_date.getHours();
var mm = new_date.getMinutes();
var ss = new_date.getSeconds();
var new_time = hh + parseInt(min_hr);
if (new_time > 24) {
new_time = new_time - 24;
new_date.setDate(new_date.getDate()+1);
}
if(date1.getTime() > new_date.getTime(){ // where did date1 come from?
if(hour1 > new_time){
alert("message")
}
else if (hour1 == new_time && min1 <= mm){
alert("message")
}
}
else if (date1.getTime() == new_date.getTime() {
if(hour1 < new_time){
alert('message');
}
else if (hour1 == new_time && min1 <= mm){
alert('mesage');
}
}
For javascript datetime manupilation I would recommend Datejs library.
It allows a flexible datetime addition and subtraction, ie.:
// Get today's date
Date.today();
// Add 5 days to today
Date.today().add(5).days();
// Get Friday of this week
Date.friday();
// Get March of this year
Date.march();
// Is today Friday?
Date.today().is().friday(); // true|false
// What day is it?
Date.today().getDayName();

Categories