Future Date Calculator - javascript

I have the following script that when used, allows the user to see a future date, while excluding weekends. The problem i've encountered though is if the current day is Friday, and i set the future date to 3 days it counts the Saturday and Sunday as working days. I'm really hoping one of you may be able to help as I'm not really that great at Javascript.
The correct example would be: If Today = Friday then 3 working days from now would be Wednesday (not Monday as the script currently calculates it).
Any ideas?
var myDelayInDays = 3;
myDate=new Date();
myDate.setDate(myDate.getDate()+myDelayInDays);
if(myDate.getDay() == 0){//Sunday
myDate.setDate(myDate.getDate() + 2);//Tuesday
} else if(myDate.getDay() == 6){//Saturday
myDate.setDate(myDate.getDate() + 2);//Monday
}
document.write('' + myDate.toLocaleDateString('en-GB'));
Any help would really be great.
Thanks

Try this code by changing date and days to add, A custom loop is used to skip sat and sun
function addDates(startDate,noOfDaysToAdd){
var count = 0;
while(count < noOfDaysToAdd){
endDate = new Date(startDate.setDate(startDate.getDate() + 1));
if(endDate.getDay() != 0 && endDate.getDay() != 6){
//Date.getDay() gives weekday starting from 0(Sunday) to 6(Saturday)
count++;
}
}
return startDate;
}
var today = new Date();
var daysToAdd = 3;
alert(addDates(today,daysToAdd));

Related

Javascript how to get full two year from current month?

I have question about getting full two years from the current date. So what i did id get the current month using the new date function and used the for loop to print each of the month. But, i cant really get it to work.... I will post the code that i did below. I would be really appreciate it if anyone can tell me the logic or better way of doing it.
For example: if today current date is august it store into an array from 8 / 2020 9/ 2020 ..... 12/ 2020, 1/2021 and goes to another year to 8/2022.
var d = new Date();
var year = d.getFullYear();
var dateStr;
var currentYear;
var storeMonthYear = [];
for(var i = 1; i <= 24; i++){
dateStr = d.getMonth() + i
currentYear = year;
if(dateStr > "12"){
dateStr = dateStr - 12
// currentYear = year;
// if(currentYear){
// }
storeMonthYear[i] = dateStr + "/" + (currentYear + 1);
}
else if(dateStr > "24"){
storeMonthYear[i] = dateStr + "/" + (currentYear + 1);
}
else{
storeMonthYear[i] = dateStr + "/" + currentYear;
}
storeMonthYear[i] = d.getMonth() + i
}
export const settlementPeriod = [
{
MonthYearFirstRow1: storeMonthYear[1],
MonthYearFirstRow2: storeMonthYear[2],
MonthYearFirstRow3: storeMonthYear[3],
MonthYearFirstRow4: storeMonthYear[4],
MonthYearFirstRow5: storeMonthYear[5],
MonthYearFirstRow6: storeMonthYear[6],
MonthYearFirstRow7: storeMonthYear[7],
MonthYearFirstRow8: storeMonthYear[8],
MonthYearFirstRow9: storeMonthYear[9],
MonthYearFirstRow10: storeMonthYear[10],
MonthYearFirstRow11: storeMonthYear[11],
MonthYearFirstRow12: storeMonthYear[12],
MonthYearSecondRow13: storeMonthYear[13],
MonthYearSecondRow14: storeMonthYear[14],
MonthYearSecondRow15: storeMonthYear[15],
MonthYearSecondRow16: storeMonthYear[16],
MonthYearSecondRow17: storeMonthYear[17],
MonthYearSecondRow18: storeMonthYear[18],
MonthYearSecondRow19: storeMonthYear[19],
MonthYearSecondRow20: storeMonthYear[20],
MonthYearSecondRow21: storeMonthYear[21],
MonthYearSecondRow22: storeMonthYear[22],
MonthYearSecondRow23: storeMonthYear[23],
MonthYearSecondRow24: storeMonthYear[24]
},
];
Create the date from today, get the month and year. Iterate from 0 to 24 for now till in 24 months. If month is 12 than set month to 0 and increment the year. Push the new datestring. Increment the month for the next step.
Note: Beacsue JS counts months form 0-11 you had to add for the datestring 1 for the month and make the change of year at 12 and not 13.
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth();
let res=[];
for (let i=0; i<=24; i++) {
if (month===12) {
month = 0;
year++;
}
res.push(month+1 + '/' + year);
month++;
}
console.log(res);
Here you go, you get an array of strings like "8/2020","9/2020" etc from starting month to the last month including both( in total 25 months).
If you don't want to include last month just delete +1 from for loop condition.
let currentDate = new Date();
let settlementPeriod = [];
let numberOfMonths = 24;
for(let i=0;i<numberOfMonths+1;i++){
settlementPeriod.push(currentDate.getMonth()+1+"/"+currentDate.getFullYear()); //We add current date objects attributes to the array
currentDate = new Date(currentDate.setMonth(currentDate.getMonth()+1)); //Every time we add one month to it
}
console.log(settlementPeriod);
There are a couple of things that stick out in your code sample:
You're comparing strings and numbers (e.g. dateStr > "12"). This will lead to some weird bugs and is one of JS's most easily misused "features". Avoid it where possible.
You increment the year when you reach 12 months from now, rather than when you reach the next January
You're overwriting your strings with this line storeMonthYear[i] = d.getMonth() + i so your array is a bunch of numbers rather than date strings like you expect
Here's a code sample that I think does what you're expecting:
function next24Months() {
const today = new Date()
let year = today.getFullYear()
let monthIndex = today.getMonth()
let dates = []
while (dates.length < 24) {
dates.push(`${monthIndex + 1}/${year}`)
// increment the month, and if we're past December,
// we need to set the year forward and the month back
// to January
if (++monthIndex > 11) {
monthIndex = 0
year++
}
}
return dates
}
In general, when you're dealing with dates, you're probably better off using a library like Moment.js - dates/times are one of the most difficult programming concepts.
While #Ognjen 's answer is correct it's also a bit waseful if your date never escapes its function.
You don't need a new date every time:
function getPeriods(firstMonth, numPers){
var d = new Date(firstMonth.getTime()); // clone the start to leave firstMonth alone
d.setDate(1); // fix after #RobG
var pers = [];
var m;
for(var i = 0; i< numPers; i++){
m = d.getMonth();
pers.push(`${m+ 1}/${d.getFullYear()}`)
d.setMonth(m + 1); // JS dates automatically roll over. You can do this with d.setDate() as well and when you assign 28, 29, 31 or 32 the month and year roll over automatically
}
return pers;
}

Date coming across as American Format even when explicitly told to use UK

I found an earlier question regarding pulling up dates that are marked as future here (Date should not be older than 1 year from current date (Today's date) in javascript)
This works great and is a great piece of work. The issue I'm having is the software we use tries to force everything to use USA date format and we're based in UK. This is fine, I can change the code to mark down as the correct date format for todays date (and it recognises it as UK! ... and I change the input date and it recognises it as GMT!. Great, that means it works right?)
No such luck. Whenever I select for example 06/05/2020 it marks it as 5th June. Even though it looks like all the dates are being marked to grab the UK date based on the input. (keep in mind, it's doing that for todays date). I think my confusion is coming because the console.log error is this
"This is enDateFri Jun 05 2020 00:00:00 GMT+0100 (British Summer Time)" When inputting 06/05/2020. It recognises it as GMT but not as the UK date? I did use the setlocale function to see if it made any difference but no such luck.
function validateNetworthDate() {
var dateValue = $(".eyeTest input").val();
var currentTime = new Date();
var currentDay = currentTime.getDate();
var currentMonth = currentTime.getMonth() + 1; //As January is 0!
var currentYear = currentTime.getFullYear();
if (currentDay < 10) {
currentDay = '0' + currentDay
}
if (currentMonth < 10) {
currentMonth = '0' + currentMonth
}
var enteredDay = dateValue.substr(0, 2);
var enteredMonth = dateValue.substr(3, 2);
var enteredYear = dateValue.substr(6, 4);
var enteredDateFormat = enteredDay + '/' + enteredMonth + '/' + enteredYear;
console.log(enteredDateFormat)
// var enteredDateFormat=dateValue;
//console.log("This is entered date format " + enteredDateFormat);
var enDate = new Date(enteredDateFormat);
var yearAgoTime = new Date().setFullYear(currentTime.getFullYear() - 2);
//console.log(yearAgoTime)
var compDate = currentTime - enDate;
console.log("This is enDate " + enDate)
if (compDate < 0) {
console.log("future date not allowed");
alert("future date not allowed");
$('.eyeTest input').addClass('numNeg');
}
else {
$('.eyeTest input').removeClass('numNeg');
$('.eyeTest input').addClass('numPos');
}
var compDate2 = enDate - yearAgoTime;
if (compDate2 < 0) {
console.log("More than 2 year ago not allowed.");
alert("Eye Test must be no more than 2 years ago");
$('.eyeTest input').addClass('numNeg');
}
else {
$('.eyeTest input').removeClass('numNeg');
$('.eyeTest input').addClass('numPos');
}
}

Cutoff Date with Javascript - Is this the right approach?

I currently need to display a message on an order receipt notification that let's the use know that if they placed the order before Mondays at 7:00am, that it will ship on Thursday of the same week, and if they placed the order after Mondays at 7:00am, the delivery will go on Thursday of the following week.
Unfortunately I am not a javascript developer, but here is what I got so far:
<p id="shipment_note"></p>
<script>
var today, cutDate, text;
today = new Date();
cutDate = new Date();
cutDate.getDay([1])
cutDate.setHours([0,1,2,3,4,5,6,7])
if (today.getDay() <= cutDate) {
text = "Your order will ship next Thursday" ;
} else {
text = "Your order will ship Thursday of next week.";
}
document.getElementById("shipment_note").innerHTML = text;
</script>
I'm not sure if this approach is right and wanted to get some feedback if possible.
It says, if it's sunday, or if it's monday before 7....
see getHours and getDay.
const isBeforeMondayAt7 = d=>d.getDay() === 0 ||
(d=>d.getDay() === 1 && d.getHours() < 7);
if(isBeforeMondayAt7(new Date)){
alert("Your stuff's comin this thursady");
}else{
alert("Your stuff's comin next thurzday");
}
There are a number of issues with the code:
var today, cutDate, text;
today = new Date();
cutDate = new Date();
can be
var today = new Date(),
cutDate = new Date(),
text;
Then:
cutDate.getDay([1])
does nothing. getDay doesn't take any parameters, it returns the day number in the week (0 = Sunday, 1 = Monday, etc.). The returned value isn't stored or used so this line can be removed.
cutDate.setHours([0,1,2,3,4,5,6,7])
setHours requires integer parameters, not an array. Passed as values:
cutDate.setHours(0, 1, 2, 3, 4, 5, 6, 7)
will set the date's time to 0:01:02.003. The rest of the values are ignored.
if (today.getDay() <= cutDate) {
Here you're comparing the day number to a Date object. The <= operator coerces its arguments to number, so cutDate will be the time value for the Date, which will always be larger than today.getDay() for any date after 1970-01-01T00:00:00.006.
What you want to check is:
Is it currently Monday and
is the time before 7:00?
If so, set the delivery date to Thursday. If not, set the delivery date for Thursday of the following week. I assume your week starts on Monday not Sunday.
So in that case:
var today = new Date(),
cutDate = new Date(+today),
opts = {weekday:'long', day:'numeric', month:'long'},
text;
// If it's Monday and before 7am
if (today.getDay() == 1 && today.getHours() < 7) {
// Set cutDate to Thursday
cutDate.setDate(cutDate.getDate() + 3);
text = 'Your order will ship on ' +
cutDate.toLocaleString(undefined, opts) ;
} else {
// Set cutDate to thursday of next week
cutDate.setDate(cutDate.getDate() + (11 - (cutDate.getDay() || 7)));
text = 'Your order will ship on ' +
cutDate.toLocaleString(undefined, opts) ;
}
console.log('Today is ' + today.toLocaleString(undefined, opts) + '. ' + text);
I've included a more useful message (to me anyway). ;-)
It appears you may have inverted the order of the operators inside the if statement.
Perhaps...
change this line...
if (today.getDay() <= cutDate) {
to...
if (today.getDay() =< cutDate) {
Here is a sample using a ternary operator:
var today = new Date();
var text = new String();
text = (today.getDay() == 0 || (today.getDay() == 1 && today.getHours() < 7) || today.getDay() > 3) ? "Your order will ship next Thursday" : "Your order will ship Thursday of next week";
alert(text);
How about this guys?
<script>
var today, cutDate, text;
today = new Date();
cutDate = new Date();
cutDate.getDay([1,2,3,4,])
cutDate.setHours([0,1,2,3,4,5,6,7])
if (today.getDay() >= cutDate) {
text = "Your order will ship Thursday of next week." ;
} else if (today.getDay([5,6,7,0])) {
text = "Your order will ship next Thursday";
}
document.getElementById("shipment_note").innerHTML = text;
</script>

JavaScript-set date to Friday before

I am using ASP.Net AJAX Calendar Extender to set a date in a textbox. Whilst it is simple enough to get the date from the user's selection in JavaScript, I am struggling to set the date in to a Friday.
In detail, what I am trying to do is for example, if a user selected a date which turns out to be a Tuesday, what I want to show in the textbox, is not that week's Friday, but the Friday before, i.e. the one that was 3 days before.
What I have achieved is to get the next Friday, i.e. the one coming up, but I have played around with the code in various ways to try and achieve what I want - can someone please help?
Thanks
dayToMtceSet = 5;
distance = (dayToMtceSet - currentDay) % 7;
toDate = toDate.setDate(toDate.getDate() + distance);
document.getElementById('<%= txtFromDate.ClientID%>').value = formatDate(toDate);
toDateSet = new Date(toDate);
toDateSet = toDateSet.setDate(toDateSet.getDate() + 6);
document.getElementById('<%= txtToDate.ClientID%>').value = formatDate(toDateSet);
With pure javascript jsFiddle:
if (date.getDay() === 5) {
console.log(date);
} else {
var beforeOneWeek = new Date(date.getTime() - 60 * 60 * 24 * 7 * 1000),
day = beforeOneWeek.getDay(),
diffToFriday = day > 5 ? 6 : 5 - day;
date.setDate((date.getDate() - 7) + diffToFriday);
console.log(date);
}
You could also use date.js
See jsFiddle
var date = Date.today();
if (date.getDay() === 5) {
date = Date.today();
} else {
date = date.moveToDayOfWeek(5, -1) // 5 is Friday, -1 is back one week
}

Using Javascript to automatically adjust date to 2nd Saturday of every month?

I need Javascript code for a website to automatically adjust a date. The goal is to have the code automatically adjust the following statement to be the second Saturday of every month from now until eternity:
Next membership meeting: Saturday, MONTH, DAY, YEAR 11 a.m. to noon.
Anyone have an idea? Much appreciated!
This function will get you the date object, you can pull out what you need from it:
var getMeeting = function(year, month){
var date = new Date(year, month, 1, 0, 0, 0, 0);
date.setDate(14-date.getDay());
return date;
};
alert(getMeeting(2011,5));
I didn't test but here is the basics:
//our main code
var Months = ["Jan", "Feb", "Mar", /*... you finish... */ ];
var meetingDate = getMonthlyMeeting();
document.Write( "<i>Next membership meeting:</i> Saturday, " + Months[meetingDate.getMonth()] + ", " + meetingDate.getDay() + ", " + meetingDate.getYear() + " 11 a.m. to noon.");
// call this to get the monthly meeting date
// returns a Date() object
function getMonthlyMeeting(){
var today = new Date(); //JS automatically initializes new Date()s to the current time
//first, see if today is our meeting day
var meetingDate;
var thisMonthsMeeting = getSecondTuesdayInMonth(today.getMonth(), today.getYear());
if( thisMonthsMeeting.getDay() == today.getDay() ){
// today is our meeting day!
meetingDate = today;
}
else {
if ( today.getDay() < thisMonthsMeeting.getDay() ){
// it hasn't happened this month yet
meetingDate = thisMonthsMeeting;
} else {
//this month's meeting day has already passed
if( today.getMonth() == 11 ){
// rolling over to the next year
meetingDate = getSecondTuesdayInMonth(0, today.getYear() + 1);
} else {
meetingDate = getSecondTuesdayInMonth(today.getMonth() + 1, today.getYear());
}
}
}
return meetingDate;
}
// this is a helper function to get the second tuesday in any month
// returns a Date() object
function getSecondTuesdayInMonth(var month, var year){
var saturdays = 0;
var testDay= new Date();
while( testDay.getDay() != 2 && saturdays < 2 ){
//while the day we are testing isnt tuesday (2) and we haven't found it twice
if( testDay.getDay() == 2 )
saturdays = saturdays + 1; //we found a saturday
testDay= new Date(testDay.getTime() + 86400000); //increment our day to the next day
}
//when we finish the while loop, we are on our day
return testDay;
}
So, I figure that the meat of your problem is: How do I know what the second saturday of each month is?
Not tested, but this is what I came up with:
It is abstracted for any nth day of any month.
nthDate = function(nth_week, nth_day, month){
var src_date = new Date();
src_date.setDate(1);
src_date.setMonth(month);
return ( (nth_week * 7) - src_date.getDay() ) - ( Math.abs( nth_day - 6) );
};
var cur_date = new Date();
var cur_day = cur_date.getDay();
//2 for the 2nd week of the month
//6 is the integer value for saturday (days of the week 0-6)
var nth_date = nthDate( 2, 6, cur_date.getMonth() );
if(cur_day < nth_date){
//display the upcoming date here
}else if( cur_day > nth_date){
//figure out next month's date and display that
var next_date = nthDate(2, 6, (cur_date.getMonth() +1) );
//does this deal with the case of the month being december?? not sure.
}
The 2nd week is in the range of 14 days into the month.
We can:
first subtract the offset for the day of the week that this month starts with,
then second:
we can subtract the offset for the day of the week that we are looking for.
(this needs to be the offset of days, so saturday is a 0 (zero) offset. We get this value from the absolute value of nth day minus the number of days in the week.
This gives us the date of the second saturday.
Then, because you have some ints you can do a simple compare against the values.
If we're before the second saturday, display that, if not calculate a new date for next month.
Hope that helps.

Categories