Product shipping time counter in Javascript - javascript

I need a counter that counts values:
Days, e.g. 1, when ordering by 10:30 am, the change should be for 2 days after that time. Of course, the counter must also ignore the weekends.
So, buy on Friday at 14/10/2022 10:00, the date of dispatch should be on 17/10/2022. However, when ordering 14/10/2022 12:00, the shipping date should be on 18/10/2022.
it would be good to count down the time for submission to 10:30
function setShipDate () {
// element to write date to
var shipdate = document.getElementById("date");
// Set start date to today - end date in 2 days
var startDate = new Date();
var endDate = "", noOfDaysToAdd = 1, count = 0;
// Map numeric month to name
var month = new Array();
month[0] = "01";
month[1] = "02";
month[2] = "03";
month[3] = "04";
month[4] = "05";
month[5] = "06";
month[6] = "07";
month[7] = "08";
month[8] = "09";
month[9] = "10";
month[10] = "11";
month[11] = "12";
while(count < noOfDaysToAdd){
// add a day to the end date each loop
endDate = new Date(startDate.setDate(startDate.getDate() + 1));
// only count when not a weekend
if(endDate.getDay() != 0 && endDate.getDay() != 6){
count++;
}
}
// update shipdate HTML
shipdate.innerHTML= endDate.getDate() + '.' + month[endDate.getMonth()] + '.' + endDate.getFullYear();
}
setShipDate();
Scheduled shipment: <span id = "date">
Surely it is possible to simplify this code + add this extra function mentioned above.
<today date> // today's date
<text id = "time"> // how much time I have left for the order with shipment:
<text id = "date"> // the end date according to the schedule until 10:30

var shipdate = document.getElementById("date");
let newDate = new Date();
// GET ORDER TIME
let orderHour = newDate.getHours();
let orderMinute = newDate.getMinutes();
let orderWeekDay = newDate.getDay();
// default delivery time
let deliverAfterDays = 1;
// delivery after weenkend
if (orderWeekDay == 5) {
deliverAfterDays = 3;
}
// Do deliveriy according to tomorrow's slot
if ((orderHour*60+orderMinute) > 630) {
deliverAfterDays++;
}
let deliveryDate = new Date(newDate.setDate(newDate.getDate() + deliverAfterDays));
const prefix0 = (n) => {
if (n <= 9) {
return "0"+n;
}
return n.toString();
}
shipdate.innerHTML= deliveryDate.getDate() + '.' + prefix0(deliveryDate.getMonth()) + '.' + deliveryDate.getFullYea();
I think this will solve your problem

Related

How to compare two Dates both Month and Year in Jquery

I have the following date picker fields in my view. I want to validate that fromDate must be less than todate.
#(Html.Kendo().DatePickerFor(m => m.FromDate)
.Format("{0:MM/yyyy}")
.Depth(CalendarView.Year)
.Start(CalendarView.Year)
)
And From Date
#(Html.Kendo().DatePickerFor(m => m.ToDate)
.Format("{0:MM/yyyy}")
.Depth(CalendarView.Year)
.Start(CalendarView.Year)
)
I used this Jquery but it only check the month Part. How can compare both the month and the year
function validateDateRange() {
var messageText = '';
var fromDate = $('#FromDate').val();
var toDate = $('#ToDate').val();
if ((fromDate > toDate) && (toDate != null || toDate.length != 0) && (fromDate != null || fromDate.length != 0)) {
messageText = 'start Date Must be greater than or equal to the end date.';
}
return messageText;
}
You can just change the date values into timestamp
function validateDateRange() {
var messageText = '';
var fromText = $('#FromDate').val();
var toText = $('#ToDate').val();
// since from/to texts has different date format we need to change it
// to a format new Date() would accept
var fromSplit = fromText.split("/");
var toSplit = toText.split("/");
// just put 1 day if it's not necessary
fromText = fromSplit[1] + "-" + fromSplit[0] + "-" + "1";
toText = toSplit[1] + "-" + toSplit[0] + "-" + "1";
// multiplying date by 1 will return a timestamp
var fromDate = new Date(fromText) * 1;
var toDate = new Date(toText) * 1;
/* Shouldn't be start date be lesser than end date? but whatever */
if (fromDate < toDate) {
messageText = 'start Date Must be greater than or equal to the end date.';
}
return messageText;
}
try Moment.js it has a lot for features, you can simply calculate like this.
var a = moment([2008, 9]);
var b = moment([2007, 0]);
a.diff(b, 'years'); // 1
a.diff(b, 'years', true); // 1.75
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1

Javascript Date +15 Days

I want this day to be 25 days from now, and it needs to correspond with normal workday measurements. Saturdays, Sundays and Holidays need to be removed. I've tried using Google sheets and javascript:
Here is what I have.
function Calendar() {
var now = new Date();
var year = now.getFullYear();
var month = new Array();
month[0] = "01";
month[1] = "02";
month[2] = "03";
month[3] = "04";
month[4] = "05";
month[5] = "06";
month[6] = "07";
month[7] = "08";
month[8] = "09";
month[9] = "10";
month[10] = "11";
month[11] = "12";
var monthnum = month[now.getMonth()];
var weekday = new Array();
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var day = weekday[now.getDay()];
var date = now.getDate();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Schedule");
var last = sheet.getLastRow();
var destination = sheet.getRange(last, 1);
var format = sheet.getRange(10, 1, 1, 7);
var insertdate = sheet.getRange(last, 2);
var insertday = sheet.getRange(last, 1)
sheet.insertRowAfter(last);
sheet.deleteRow(7)
insertdate.setValue(monthnum + "/" + date + "/" + year);
insertday.setValue(day)
Logger.log(monthnum + "/" + date + "/" + year + " " + day)
}
There are many ways to do it, but the easily one is: 86400000 is one day
86400000= 24 Hours * 60 Min * 60 Seconds * 1000 Milliseconds
Here is an example which may help you:
var first = new Date();
var last = new Date(new Date(first).getTime() + (86400000 * 25));
var now = new Date(); now.setDate(now.getDate() + 25);
console.log(first);
console.log(last);
console.log(now);

Get month number from a date in javascript

I have a daterangepicker function that is returning the selected date in this format 06 May 2016. What I am trying to do is extract the month as an integer, therefore from the above I should be able to return the number 5.
This is the line of code that returns the selected date - getDateString(new Date(opt.start)
Any help is appreciated thanks.
var date = new Date();
var month = date.getMonth();
The getMonth() method returns the month (from 0 to 11) for the specified date, according to local time.
var datestring = getDateString(new Date(opt.start);
var monthNumber = new Date(datestring).getMonth()+1;
I'm not sure this will help since I am new in this field
var today = new Date();
var month = new Array();
month[0] = "01";
month[1] = "02";
month[2] = "03";
month[3] = "04";
month[4] = "05";
month[5] = "06";
month[6] = "07";
month[7] = "08";
month[8] = "09";
month[9] = "10";
month[10] = "11";
month[11] = "12";
var monthNumber = month[today.getMonth()];
console.log("This month is " + monthNumber);
Thanks, and more simple:
var month = new Date().getMonth() + 1;
// Result, ie: January = 1 ... December = 12
var month = new Date().getMonth() + 1;
console.log("month", month);

My highlighted current date via javascript is not showing correctly

I have successfully managed (with the help from stack overflow) to loop through a calendar starting from may until end oktober 2015. now i want to highlight the current date which is 28 june sunday. but for some reason it highlights the wrong date and i don't think its because of the code but i am not a 100% sure.
checkout this link to see it visually (http://gyazo.com/30e448d0f84c8f1c55e4dd1ce6d91f38)
jsfiddle link: https://jsfiddle.net/GY22/vqfk8yLL/
this is my html code:
<ul id="timeline">
<li></li>
</ul>
this is my javascript code:
<script>
// Get today's current date.
var now = new Date();
console.log(now);
// Calculates the number of the week
var weekNumber = ((now.getDate()<10) ? "0" : "")+ now.getDate();
console.log("The current week number is: " + weekNumber);
// Array list of months.
var month = new Array(12);
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
//console.log(month[3]);
var weekDay = new Array(7);
weekDay[0]= "Su";
weekDay[1] = "Mo";
weekDay[2] = "Tu";
weekDay[3] = "We";
weekDay[4] = "Th";
weekDay[5] = "Fr";
weekDay[6] = "Sa";
function formatDate(date) {
var month = date.getUTCMonth() +1;
var dayNumber = date.getUTCDate();
var year = date.getUTCFullYear();
var day = date.getUTCDay();
return weekDay[day] + ": " + dayNumber + "-" + month + "-" + year + "; ";
//return weekDay[day] + " " + dayNumber + "; ";
}
//console.log(formatDate(new Date()));
var today
function addListItem(){
var createListItem = document.createElement("li");
var outputListItem = document.createTextNode(today);
createListItem.appendChild(outputListItem);
var createUl = document.getElementsByTagName("ul");
createUl[0].appendChild(createListItem);
}
// loop starting from may up untill for months from the set date
for (var i = 0; i < 122; i++){
today = formatDate(new Date(2015, 05, i));
//document.write(today + "<br />");
addListItem();
}
document.getElementById('timeline').
getElementsByTagName('li')[(new Date()).getDate() - 1].className += ' currentDate';
Change the last line from:
getElementsByTagName('li')[(new Date()).getDate() - 1].className += ' currentDate';
To:
getElementsByTagName('li')[(new Date()).getDate() + 1].className += ' currentDate';
The date appeared to be off by just one day before, so that should fix it.
Consider using MomentJS instead. It would save you a lot of code and date problems:
http://momentjs.com/
If you prefer to keep your code, move your current date logic inside your addListItem() method.
if(today == formatDate(new Date())) {
createListItem.className += ' currentDate';
}

Delivery Date Javascript Adapt To Exclude Weekends

I have been currently using this script
<script type="text/javascript">
var _next = new Date(new Date() * 1 + 24*60*60*1000*9);
document.write(" Your expected delivery date is " + (_next.getMonth() + 1) + "/" + _next.getDate() + "/" + _next.getFullYear());
</script>
I'm wondering how do I get it to exclude weekends if possible.
Just add hours if you like. this is a code that expects to deliver the next working day.
function myFunction() {
var d = new Date();
var weekday = new Array(7);
weekday[0] = "sunday";
weekday[1] = "monday";
weekday[2] = "tuesday";
weekday[3] = "wednesday";
weekday[4] = "thursday";
weekday[5] = "friday";
weekday[6] = "saturday";
var monthday = new Array(12);
monthday[0] = "01";
monthday[1] = "02";
monthday[2] = "03";
monthday[3] = "04";
monthday[4] = "05";
monthday[5] = "06";
monthday[6] = "07";
monthday[7] = "08";
monthday[8] = "09";
monthday[9] = "10";
monthday[10] = "11";
monthday[11] = "12";
if (d.getDay() > 0 && d.getDay() <= 4) {
d.setHours(d.getHours() + 24);
var deliver = weekday[d.getDay()];
var day = d.getDate();
var month = monthday[d.getMonth()];
var year = d .getFullYear();
document.getElementById("deliveryday").innerHTML = deliver + ' ' + day + '-' + month + '-' + year;
} else if (d.getDay() == 0) {
d.setHours(d.getHours() + 48);
var deliver = weekday[d.getDay()];
var day = d.getDate();
var month = monthday[d.getMonth()];
var year = d .getFullYear();
document.getElementById("deliveryday").innerHTML = deliver + ' ' + day + '-' + month + '-' + year;
} else {
d.setHours(d.getHours() + 72);
var deliver = weekday[d.getDay()];
var day = d.getDate();
var month = monthday[d.getMonth()];
var year = d .getFullYear();
document.getElementById("deliveryday").innerHTML = deliver + ' ' + day + '-' + month + '-' + year;
}
}
myFunction()
<script type="text/javascript">
<!--
var myDate=new Date();
if ( myDate.getHours() < 12 ) // less than 12pm
{
var daystodeliver = [7,5,5,5,5,8,7][myDate.getDay()];
}
else
{
var daystodeliver = [7,7,7,7,7,9,8][myDate.getDay()];
}
myDate.setDate(myDate.getDate()+daystodeliver);
document.write(['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'] [myDate.getDay()]);
var dayofmonth = myDate.getDate();
suffix = ((dayofmonth < 10)||(dayofmonth > 20)) ? ['th','st','nd','rd','th','th','th','th','th','th'][dayofmonth % 10] : 'th';
document.write(' ' + dayofmonth + suffix + ' ');
document.write(['January','February','March','April','May','June','July','August','Septembe r','October','November','December'][myDate.getMonth()]);
// -->
Try this:
function deliver(inDays, startingOn){
var s, f = 0, d;
if(!inDays)inDays = 0;
s = !startingOn ? new Date : new Date(startingOn);
for(var i=0,n,t=0,l=inDays; i<l; i++,t+=86400000){
n = new Date(s.getTime()+t).getDay();
if(n === 0 || n === 6)f++;
}
d = new Date(s.getTime()+86400000*(inDays+f));
return 'Your expected delivery date is '+d.toLocaleDateString();
}
// same day delivery
console.log(deliver());
// deliver in 9 days stating today
console.log(deliver(9));
// deliver in 9 days starting on October 12, 2013 - must be a valid Date String
console.log(deliver(9, 'October 12, 2013'));
/* Note that in the last example the Date starts on the weekend, therefore same
day becomes Monday, which if you don't work weekends is the first day you
would see the order anyways.
*/
This is good to show your Client when something is delivered. Make sure you set the actual date it your database, according to where you are, using a Server Side language like PHP.
You should pay me for this since it will work even on a leap year. Ha!
Try this to get the date
I wrote a routine that you supply a date object, apply the menthod, the public holidays in a separate list is passed and any holidays / public holidays including weekends are skipped over.
Its this post
// array of ISO YYYY-MM-DD format dates
publicHolidays = {
uk:["2020-01-01","2020-04-10","2020-04-13","2020-05-08","2020-05-25",
"2020-08-03","2020-08-31","2020-12-25","2020-12-28"],
usa:["2020-01-01","2020-01-20","2020-02-14","2020-02-17","2020-04-10",
"2020-04-12","2020-05-10","2020-05-25","2020-06-21","2020-07-03",
"2020-07-04","2020-09-07","2020-10-12","2020-10-31","2020,11,11",
"2020-11-26","2020-12-25"]
}
// check if there is a match in the array
Date.prototype.isPublicHoliday = function( data ){// we check for a public holiday
if(!data) return 1;
return data.indexOf(this.toISOString().slice(0,10))>-1? 0:1;
}
// calculation of business days
Date.prototype.businessDays = function( d, holidays ){
var holidays = holidays || false, t = new Date( this ); // copy date.
while( d ){ // we loop while d is not zero...
t.setDate( t.getDate() + 1 ); // set a date and test it
switch( t.getDay() ){ // switch is used to allow easier addition of other days of the week
case 0: case 6: break;// sunday & saturday
default: // check if we are a public holiday or not
d -= t.isPublicHoliday( holidays );
}
}
return t.toISOString().slice(0,10); // just the YYY-MM-DD
}
// dummy var, could be a form field input
OrderDate = "2020-02-12";
// test with a UK holiday date
var deliveryDate = new Date(OrderDate).businessDays(7, publicHolidays.usa);
// expected output 2020-02-25
console.log("Order date: %s, Delivery date: %s",OrderDate,deliveryDate );

Categories

Resources