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

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>

Related

Get last 7 days by names javascript

How to get the last seven days, from today, (by names) in java script.
like if today is Wednesday, I want to get it like (Wednesday, Tuesday, Monday, Sunday, Saturday, Friday, Thursday, Wednesday).
Just add the days in the string array and iterate them backward by getting current date with new Date() this will return the index of current day
const weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
const d = new Date();
let day = weekday[d.getDay()];
var wanteddays = 8;
var temp = d.getDay()
while(wanteddays!=0){
if (temp <0)
temp = 6;
console.log(weekday[temp]);
temp = temp-1;
wanteddays = wanteddays -1;
}
function getDayName(date, len, local) {
let newDate = new Date(date);
let weekDays = [];
Array(len).fill(1).forEach((subDay) => {
newDate.setDate(newDate.getDate() - subDay);
weekDays.push(newDate.toLocaleDateString(local, { weekday: 'long' }));
})
return weekDays;
}
to use:
getDayName(Date.now(), 7, 'en-EN')
OR
getDayName('10/12/2022', 7, 'en-EN')
Typescript:
function getDayName(date: Date | string | number, len: number, local:string) {
let newDate = new Date(date);
let weekDays: string[] = [];
Array(len).fill(1).forEach((subDay: number) => {
newDate.setDate(newDate.getDate() - subDay);
weekDays.push(newDate.toLocaleDateString(local, { weekday: 'long' }));
})
return weekDays;
}
This should order an array to follow your wished output.
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var currentDay = days[ (new Date()).getDay()]
days = days.reverse();
var x = days.indexOf(currentDay)
var daysLastSeven = days.slice(x).concat(days.slice(0,x))
console.log(daysLastSeven)

Trying to get first date of current month in html date picker

Hi I am trying to get first date of current month in HTML date picker.
From <input type="date" id="fdate" value=""/>
To<input type="date" id="tdate" value=""/>
I get today date in id="tdate like this given below but starting date of current month not able to get as I get current date.
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var today = year + "-" + month + "-" + day;
document.getElementById("tdate").value = today;
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
document.getElementById("tdate").value = firstDay;
date input fields must be in YYYY-MM-DD format. Your code:
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
Will give back a string, e.g. Tue Sep 01 2020 00:00:00 GMT-0400 (Eastern Daylight Time), which is not what you want.
You can combine a couple of existing StackOverflow answers to accomplish what you want:
// https://stackoverflow.com/a/23593099/378779
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
// https://stackoverflow.com/a/13572682/378779
function getFstDayOfMonFnc() {
var date = new Date();
return new Date(date.getFullYear(), date.getMonth(), 1)
}
Assuming fdate should be the first of the month and tdate should be today's date:
document.getElementById('fdate').value = formatDate( getFstDayOfMonFnc() );
document.getElementById('tdate').value = formatDate( new Date() );
var date = new Date();
var monthStart = Date.UTC(date.getFullYear(), date.getMonth())
monthStart = toIsoDateString(monthStart);
console.log(monthStart);
var nextMonthStart = Date.UTC(date.getFullYear(), date.getMonth() + 1);
nextMonthStart = toIsoDateString(nextMonthStart);
console.log(nextMonthStart);
function toIsoDateString(utcDate) {
var date = new Date(utcDate);
return date.toISOString().split('T')[0];
}
I also had made such a program but there were a few changes, instead of just the first date I was getting the current time, the first day of the month and also the last date of the month.
This is the code I used:
<html>
<head>
<title>JavaScript Dates</title>
</head>
<body>
<script>
var date = new Date();
document.write("Current Date: " + date );
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
document.write("<br>"+firstDay);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
document.write("<br>"+lastDay);
</script>
</body>
</html>
You can edit this code and try working out.

Javascript. Help scheduling dates

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);
}

JS dates, first day of the month

i'm programming a calendar and i need to know what the first day of each month is. Like, This month, hte first day was on a sunday. How would i go about to figure that out for all months of the year? Or any month for that matter.
Thanks in advance!
edit: the day can be returned as an integer.
Where options for toLocaleString are supported, you can use it to get the day name in the browser default language:
function getDayName(date) {
return date.toLocaleString(undefined, {weekday:'long'});
}
function getMonthName(date) {
return date.toLocaleString(undefined, {month:'long'});
}
// Create a date
var d = new Date();
// Set to first of month
d.setDate(1);
// Create string
console.log(`The first of ${getMonthName(d)} was a ${getDayName(d)}.`);
Of course mixing English with some other language may not be appropriateā€¦
You could create a method that returns the day name
function(year, month){
var date = new Date(year, month, 1);
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
return days[date.getDay()];
}
JavaScript already provides this out of the box be using getDay.
new Date().getDay()
This will return 0-6. Depends on what weekday it is.
If you need it as a readable string you may want to do something like this:
var weekdays = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
];
console.log(weekdays[new Date().getDay()]);
Knowing this you can go furter:
const year = new Date().getFullYear();
const weekdays = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
];
[0,1,2,3,4,5,6,7,8,9,10,11].forEach(x => {
const weekday = new Date(year, x, 1).getDay();
console.log(weekdays[weekday]);
});
See: MDN
I would highly recommend using MomentJS library if you are not already using it. Using moment, you can get the day of 1st of any month using this single statement:
moment("2017-11-01").startOf('month').format("dddd")
If you cannot use moment for some reason, then you could just create a function that takes in month and year and returns back the day of 1st of that month. You need to use Date.prototype.getDay() for this, which returns a value from 0 to 6, where 0 means Sunday.
$("#get-day").on("click", function(e){
var year = $("#year").val();
var month = $("#month").val();
alert( getDay(year, month) );
});//#get-day click()
function getDay(year, month){
var days = ["Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"];
var dayIndex = new Date(year + "-" + month + "-01").getDay();
return days[ dayIndex ];
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="year" value="2017" />
<input type="text" id="month" value="10" />
<button id="get-day">Get Day on 1st</button>
The .getDay() method returns an integer, the day of the week for the specified date according to local time, where Sunday = 0 and Saturday = 6. Here's an example using this:
dateFunction = function(myDate){
var days =
["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
var dayInt = new Date(myDate).getDay()
return days[dayInt]
}
var FirstDayOfOctober = dateFunction("2017-10-01");

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.

Categories