Javascript. Help scheduling dates - javascript

I am helping a friend in his mini project and at this moment we are standing in the following situation: For example a doctor tells his patient that as of TODAY you have X numbers of consultations, every Wednesday and Friday, how to get the dates of these consultations, assuming that TODAY, it can be any day of the week ???
Thanks

I'm not sure if that is what you want but you can achieve that, for example, like this.
//get current date
var date = new Date ()
//array with week-day names
var week_days = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
];
//your initial variables
var consultations = ['Wednesday', 'Friday'];
var X = 5;
//loop through X + 1 weeks to find dates and count results
var count = 0
for (var i = 0; i < (X + 1) * 7; i++) {
//get name of date-day
var week_day = week_days[date.getDay ()];
//check if wanted
if (consultations.indexOf (week_day) != -1) {
//construct date and output
var day = date.getDate ();
var month = date.getMonth ();
var year = date.getFullYear ();
document.write (day + '.' + month + '.' + year);
document.write ('<br/>');
//increment count
count++;
//stop if count == X
if (count == X)
break;
}
//increment date
date.setDate (date.getDate () + 1);
}

Related

Find day of week of any year, plusYears() function Not Working

I've done a bit of searching and either haven't found an example that fits, or perhaps I just can't quite grasp some of concepts yet.
I'm trying to write a function that lets the user input a date (from a form) and return every year where the date falls on a Friday over the next 50 years. I'm sure there are several things wrong with my initial approach, but my primary concern is the .plusYears() function is not working. Thanks for any feedback!
<script>
function date() {
var weekday = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
var input = document.getElementById("input").value;
var date = new Date(input).getUTCDate();
console.log("date: " + date);
for (var i = 0; i < 50; i++){
date = date.plusYears(i);
console.log("date: " + date);
if(date.getDay() == 6){
document.getElementById('output').textContent = date.getDate() + ", " + weekday[date];
}
}
}
</script>
<form>
<input type="date" placeholder="dd:mm:yy" id="input" />
<input type="button" value="weekday" onclick="date()" />
</form>
<p id="output"></p>
EDIT:
function date() {
var input = document.getElementById("input").value;
var date = new Date(input);
for (var i = 0; i < 50; i++) {
var y = 1;
date = new Date(date.getFullYear() + y, date.getMonth(), date.getDate());
if(date.getDay() == 5){
console.log("friday" + date);
}
else{
console.log("other day");
}
}
}
Unsure why the console is displaying the date prior to whichever the user inputs.
plusYear()? where did you get this function from?
try something like
date.setFullYear(date.getFullyear() + i);
should work.
Yes, plusYears isn't a function on Date. I use the method recommended in this question to construct a new date (date = new Date(date.getFullYear() + i, date.getMonth(), date.getDate())). Also, Friday is day 5 (not day 6). See inline comments below:
<script>
function date() {
var weekday = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
var input = document.getElementById("input").value;
var date = new Date(input);
console.log("date: " + date);
for (var i = 0; i < 50; i++) {
date = new Date(date.getFullYear() + i, date.getMonth(), date.getDate()); // construct new date like this
console.log("date: " + date);
if (date.getDay() == 5) { // Friday is 5 (not 6)
// use date.getDay() to get the correct index of the day name in your week array.
// Also, append this new value so that it doesn't overwrite the other.
// You may want to add formatting etc.
document.getElementById('output').append(document.createTextNode(date + ", " + weekday[date.getDay()]));
}
}
}
</script>
<form>
<input type="date" placeholder="dd:mm:yy" id="input" />
<input type="button" value="weekday" onclick="date()" />
</form>
<p id="output"></p>

Calculate days excluding weekend and holiday in JavaScript

I am trying to write a code where total days will be counted excluding weekends and custom defined holiday. I searched through stackoverflow and adobe forum to find a solution and came with below code.
If public holiday falls in a working day (Saturday-Wednesday) it is excluding from calculation.
My problem is that if public holiday falls in weekend (Thursday-Friday), it is deducting for both (holiday & weekend). Suppose leave duration is 18/09/2018-22/09/2018, total count 2 days is showing in place of 3. Again for 17/10/2018-21/10/2018, total count 1 day is showing in place of 3 days.
Any help or any idea to solve the problem would be great!
Regards
//Thursday and Friday will be excluded as weekend.
var start = this.getField("From").value;
// get the start date value
var end = this.getField("To").value;
var end = util.scand("dd/mm/yyyy H:MM:SS", end + " 0:00:00");
var start =util.scand("dd/mm/yyyy H:MM:SS", start + " 0:00:00");
event.value = dateDifference(start, end);
function dateDifference(start, end) {
// Copy date objects so don't modify originals
var s = new Date(+start);
var e = new Date(+end);
// Set time to midday to avoid daylight saving and browser quirks
s.setHours(12,0,0,0);
e.setHours(12,0,0,0);
// Get the difference in whole days
var totalDays = Math.round((e - s) / 8.64e7);
// Get the difference in whole weeks
var wholeWeeks = totalDays / 7 | 0;
// Estimate business days as number of whole weeks * 5
var days = wholeWeeks * 5;
// If not even number of weeks, calc remaining weekend days
if (totalDays % 7) {
s.setDate(s.getDate() + wholeWeeks * 7);
while (s < e) {
s.setDate(s.getDate() + 1);
// If day isn't a Thursday or Friday, add to business days
if (s.getDay() != 4 && s.getDay() != 5) {
++days;
}
}
}
var hdayar = ["2018/02/21","2018/03/17","2018/03/26","2018/04/14","2018/05/01","2018/08/15","2018/09/2 1","2018/10/18","2018/10/19","2018/12/16","2018/12/25"];
//test for public holidays
var phdays = 0;
for (var i = 0; i <hdayar.length; i++){
if ((Date.parse(hdayar[i]) >= Date.parse(start)) && (Date.parse(hdayar[i]) <= Date.parse(end))) {phdays ++;}}
return days-phdays + 1;
}
You should use a library for this rather than reinventing the wheel.
But if you want to do it yourself you could use .getDay to check if the public holidays are on a weekend.
var weekend = [4, 5], // for Thursday, Friday
holDate, holDay;
for (var i = 0; i < hdayar.length; i++){
holDate = Date.parse(hdayar[i]);
holDay = new Date(holDate).getDay()
if (weekend.indexOf(holDay) == -1 && holDate >= Date.parse(start) && holDate <= Date.parse(end)) {
phdays ++;
}
}
phdays will now contain the number of non-weekend public holidays within the range.
Just have the same requirement and this is the my work around.Hope it helps other
var holiday = ["4/18/2019", "4/19/2019", "4/20/2019", "4/25/2019", "4/26/2019"];
var startDate = new Date();
var endDate = new Date(startDate.setDate(startDate.getDate() + 1));
for (i = 0; i < holiday.length; i++) {
var date = endDate.getDate();
var month = endDate.getMonth() + 1; //Months are zero based
var year = endDate.getFullYear();
if ((month + '/' + date + '/' + year) === (holiday[i])) {
endDate = new Date(endDate.setDate(endDate.getDate() + 1));
if (endDate.getDay() == 6) {
endDate = new Date(endDate.setDate(endDate.getDate() + 2));
} else if (endDate.getDay() == 0) {
endDate = new Date(endDate.setDate(endDate.getDate() + 1));
}
}
}
Here, end date gives you next working day.Here,I'm ignoring current day and start comparing from Next day whether it's holiday or weekend.You can customize dateTime as per your requirement (month + '/' + date + '/' + year).Careful whenever you compares two dates with each other. Because it looks same but actually it's not.So customize accordingly.

Print weekdays and check if a date exists for this weekday

I have an array of dates
date_array = ["date1", "date2", "date3"]
I would like to print
Tuesday: Yes
Wednesday: No
Thursday: No
Friday: Yes
Saturday: No
Sunday: Yes
where Yes and No depends on whether there is a date in date_array on this weekday in the current week and the order of the weekdays should start from today's weekday.
I am using moment where the weekday number can be formatted with e, so I get the number of today's weekday with moment().format('e'). Alternatively, it could be with moment().day() where sunday=0.
I guess I could do something like
// Existing dates
var dates = [moment(), moment().add(3, 'days'), moment().add(5, 'days')]
// All weekdays to print
var weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
// Reorder
var today_weekday = moment().day()
var weekdays_reordered = weekdays.splice(today_weekday).concat(weekdays)
// Print
weekdays_reordered.map((weekday, i) => {
console.log(weekday + ': ' + (dates.some(date => date.day() === i) ? 'Yes' : 'No'));
});
<script src="https://momentjs.com/downloads/moment.min.js"></script>
But I'm not sure how exactly to make it work.
If I understood correctly, you need to print every day from current day until the end of the week, i.e. Sunday? Then, you need to set today_weekday as moment().day() - 1 (because of the indices), and then exit the loop when you get to Monday (changed it from map() to a for(), because you can't break out of map). Lastly, compare the date formated to dddd (the weekday name) to the current weekday element in the loop. Something like this:
var dates = [moment(), moment().add(4, 'days'), moment().add(5, 'days')]
// All weekdays to print
var weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
// Reorder
var today_weekday = moment().day() - 1;
var weekdays_reordered = weekdays.splice(today_weekday).concat(weekdays)
for(var i = 0; i < weekdays_reordered.length; i++) {
var weekday = weekdays_reordered[i];
if (weekday === "Monday" && i !== 0) break;
console.log(weekday + ': ' + (dates.some(date => date.format("dddd") === weekday) ? 'Yes' : 'No'));
}
<script src="https://momentjs.com/downloads/moment.js"></script>
Assuming you have an array of dates and not moment objects, you can create a date for today then check if the same date is in the array. Then step through the days of the week. Testing for date equality is a little tricky but if they are all created for say 00:00:00 then you can just check the time value.
var base = new Date();
base.setHours(0,0,0,0);
var seed = new Date(+base);
// Array of dates for today, today + 2 days, today + 4 days
var dates = [new Date(seed),
new Date(seed.setDate(seed.getDate() + 2)),
new Date(seed.setDate(seed.getDate() + 2))
];
// Test 7 days, starting from today
for (var i=7; i; --i) {
// Get weekday name in host default language
var s = base.toLocaleString(undefined, {weekday:'long'}) + ': ';
// See if there's a matching date
s += dates.find(d=>+d == +base)? 'Yes':'No';
// Add 1 to the date
base.setDate(base.getDate() + 1);
// Do something with the result
console.log(s);
}
The above requires Array.prototype.find, there's a polyfill on MDN if required. You may need to define a different comparison (predicate) function if you want to compare only date without the time.

if condition based on a string in for loop in jquery

I will explain my question in the code itself. Please see the below code
var monthNames = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
var ctdate = (new Date()).getMonth() + 1;// getting current month
var str=new Date().getFullYear()+'';
str= str.match(/\d{2}$/);//current year is 15(as this year is 2015)
var strprev= str-1;//previous year is 14
var dynmonths = new Array();
dynmonths = monthNames.slice(ctdate).concat(monthNames.slice(0, ctdate));
//here the output comes for last 12 months starting from currentmonth-12 (i.e APR in this case) to current month (i.e MAR)
//dynmonths = ["APR","MAY","JUN","JUL","AUG","SEP","AUG","SEP","OCT","NOV","DEC","JAN","FEB","MAR"];
//I am rotating dynmonths in a for loop to get full dates i.e between (01-APR-14 to 01-MAR-15)
for (var i = 0, length = dynmonths.length; i < length; i++) {
var month = '01-' + dynmonths[i] + '-' + strcurrent;
}
But the problem is that month is taking 14for all the months. Which is wrong. After 01-DEC-14 the next month must be 01-JAN-15, 01-FEB-15 and so on. How to check DEC in for loop and after DEC year must change to year+1
Thanks in advance
use below code it will work.
function ddd()
{
var monthNames = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
var ctdate = (new Date()).getMonth() + 1;// getting current month
var str=new Date().getFullYear()+'';
str= str.match(/\d{2}$/);//current year is 15(as this year is 2015)
var strprev= str-1;//previous year is 14
var dynmonths = new Array();
dynmonths = monthNames.slice(ctdate).concat(monthNames.slice(0, ctdate));
//here the output comes for last 12 months starting from currentmonth-12 (i.e APR in this case) to current month (i.e MAR)
//dynmonths = ["APR","MAY","JUN","JUL","AUG","SEP","AUG","SEP","OCT","NOV","DEC","JAN","FEB","MAR"];
//I am rotating dynmonths in a for loop to get full dates i.e between (01-APR-14 to 01-MAR-15)
for (var i = 0, length = dynmonths.length; i < length; i++) {
if(dynmonths[i]=='JAN')
{
var str = parseInt(str)+parseInt(1);
}
var month = '01-' + dynmonths[i] + '-' + str;
document.writeln(month);
document.write("<br />");
}
}
<body onload="ddd()">
You can declare variable bool = false and check if you on DEC change it to true (or use counter from more then one year):
var monthNames = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
var ctdate = (new Date()).getMonth() + 1;// getting current month
var str=new Date().getFullYear()+'';
str= str.match(/\d{2}$/);//current year is 15(as this year is 2015)
var strprev= str-1;//previous year is 14
var dynmonths = new Array();
dynmonths = monthNames.slice(ctdate).concat(monthNames.slice(0, ctdate));
//here the output comes for last 12 months starting from currentmonth-12 (i.e APR in this case) to current month (i.e MAR)
//dynmonths = ["APR","MAY","JUN","JUL","AUG","SEP","AUG","SEP","OCT","NOV","DEC","JAN","FEB","MAR"];
//I am rotating dynmonths in a for loop to get full dates i.e between (01-APR-14 to 01-MAR-15)
var isPassYear = false;
for (var i = 0, length = dynmonths.length; i < length; i++) {
var month;
if (isPassYear)
//do something
else
month = '01-' + dynmonths[i] + '-' + strcurrent;
if (monthNames[11] == dynmonths[i]) {
isPassYear = true;
}
}
second option is to use Date object and append his month by one each time, if you set append to month number 12 it automatic go to the next year.

total number of sundays in a month

I am using following code to determine total number of sundays in a month, however it gives incorrect result
function sundaysInMonth(start) {
var dat = new Date('1 ' + start);
var y = dat.getFullYear();
var m = dat.getMonth() + 1;
var days = new Date( y,m,0 ).getDate();
var sundays = [ 8 - (new Date( m + '/01/' + y ).getDay()) ];
for ( var i = sundays[0] + 7; i < days; i += 7 ) {
sundays.push( i );
}
return sundays.length;
}
When I call above functions like console.log(sundaysInMonth('September 2013')); then it returns 4 whereas September 2013 has 5 sundays.
I am getting above code from this post
Loops are not needed for this calculation.
function sundaysInMonth(start) {
var d = new Date('1 ' + start); // May not parse in all browsers
var ndays = new Date( d.getFullYear(), d.getMonth()+1, 0 ).getDate();
return Math.floor((ndays + (d.getDay() + 6) % 7) / 7);
}
Test for all months in 2013: http://jsfiddle.net/rGN28/2/
Aw, Matt beat me by one minute! I came up with basically the same solution, only with more comments. ;)
function sundaysInMonth(sMonthAndYear) {
// Get the year and month as integers
var dDate = new Date('1 ' + sMonthAndYear);
var y = dDate.getFullYear();
var m = dDate.getMonth() + 1;
// Get the number of days in the month
var iDayCount = new Date( y,m,0 ).getDate();
// Find the first Sunday
var iFirstSunday = (8 - dDate.getDay());
if (iFirstSunday > 7) {iFirstSunday = 1};
// Calculate the total number of Sundays in the month
var iSundayCount = Math.ceil ((iDayCount + 1 - iFirstSunday) / 7);
// Return the count
return iSundayCount;
}
Check this. I just fixed issue in your code
function sundaysInMonth(start) {
var dat = new Date('1 ' + start);
var y = dat.getFullYear();
var m = dat.getMonth() + 1;
var days = new Date( y,m,0 ).getDate();
var sundays = [ (8 - (new Date( m + '/01/' + y ).getDay())) % 7 ];
for ( var i = sundays[0] + 7; i < days; i += 7 ) {
sundays.push( i );
}
return sundays.length;
}
In array variable sundays we need to intially store the first day value which is a sunday. There was a small bug for months with Day 1 is sunday. For example as in your question September 2013
For these months your code will store 8 instead of 1 sundays array as first sunday. I fixed it
Although the question is old but here is my attempt to find number of Sundays in a month if anyone needs help.
<?php
$year = 2020; // Year to check
$month = 1; // Month to check (1-12)
// Get the first and last day of the month as timestamps
$firstDay = strtotime("{$year}-{$month}-01");
$lastDay = strtotime("+1 month", $firstDay);
// Initialize a counter variable
$numSundays = 0;
// Loop through each day of the month
for ($i = $firstDay; $i < $lastDay; $i = strtotime("+1 day", $i)) {
// Get the day of the week for the current day
$dayOfWeek = date("l", $i);
// If the day is Sunday, increment the counter
if ($dayOfWeek == "Sunday") {
$numSundays++;
}
}
// Print the number of Sundays
echo "Number of Sundays: $numSundays\n";
?>

Categories