Reputation: 874
I am looking for a simple function where I can pass in a string of a day for the current week, and it returns the calendar date number. For example, today, Monday June 28th. If I pass a string into the function, say, "MON", it should return 28.
source https://www.c-sharpcorner.com/UploadFile/8911c4/how-to-compare-two-dates-using-javascript/
For additional context, my end goal is to simply compare the current date with a chosen date, so see if it is in the past. I'm not really using built in date functions because the premise is that we are always in the current week and current month and current year. So all of that is already accounted for.
var currentDate = new Date();
var selectedCount = $('[id*=_WRAPPER]:has(.ncp-time) input[id]:selected').length;
var selectedDay = $('label[for=' +$('[id*=_WRAPPER]:has(.npc-time) :radio[id]:checked').attr('id') + ']').text().split('~')[0];
var selectedHour = $('label[for=' +$('[id*=_WRAPPER]:has(.npc-time) :radio[id]:checked').attr('id') + ']').text().split('~')[1].split(':')[0];
var selectedMinute = $('label[for=' +$('[id*=_WRAPPER]:has(.npc-time) :radio[id]:checked').attr('id') + ']').text().split('~')[1].split(':')[1];
if (selectedCount === 0) {
AlertMessage();
} //Alert message
function CompareDate() {
// new Date(Year, Month, Date, Hr, Min, Sec);
var currentDate = new Date();
//var chosenDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDay(), 12, 10, 00);
var currentDate = new Date();
var chosenDate = "chosenDate";
var selectedCount = $('[id*=_WRAPPER]:has(.ncp-time) input[id]:selected').length;
//MON~10:00
var selectedDay = $('label[for=' +$('[id*=_WRAPPER]:has(.npc-time) :radio[id]:checked').attr('id') + ']').text().split('~')[0];
var selectedHour = $('label[for=' +$('[id*=_WRAPPER]:has(.npc-time) :radio[id]:checked').attr('id') + ']').text().split('~')[1].split(':')[0];
var selectedMinute = $('label[for=' +$('[id*=_WRAPPER]:has(.npc-time) :radio[id]:checked').attr('id') + ']').text().split('~')[1].split(':')[1];
if (chosenDate < currentDate) {
alert("chosenDate is less than currentDate.");
}else {
alert("currentDate is greater than chosenDate.");
}
}
CompareDate();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="_WRAPPER"><span class="ncp-time"></span>
<input type="radio" name="Q26" value="3" id="Q26_3" role="radio" aria-checked="true" checked="checked" class="checked"><label for="Q26_3" class="choice-text">MON~10:00<a class="groupx003"></a></label></div>
Upvotes: 0
Views: 366
Reputation: 892
// Hmm... there is probably a quicker code golf way of doing this... however this is how I tackled something similar in the past...
function extractDateFromCurrentWeek(inputDayEnum){
const daysOfTheWeek = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'];
let datesOfTheWeek = [null, null, null, null, null, null, null];
const d = new Date();
const dayInt = d.getDay();
const date = d.getDate();
datesOfTheWeek[dayInt] = date;
// Fill out days before the current day of the week.
let revI = dayInt - 1;
let revDate = new Date();
while (revI > -1){
revDate.setDate(revDate.getDate() - 1);
datesOfTheWeek[revI] = revDate.getDate();
revI -= 1;
}
// Fill out days after the current day of the week.
let fwdI = dayInt + 1;
let fwdDate = new Date();
while (fwdI < 8){
fwdDate.setDate(fwdDate.getDate() + 1);
datesOfTheWeek[fwdI] = fwdDate.getDate();
fwdI += 1;
}
/* From here, you should now have datesOfTheWeek array filled out.
If the user inputs 'THU', find the index of that string in 'daysOfTheWeek'
array, and then, using that index... pull the corresponding value from
'datesOfTheWeek'.
*/
// PUT IN SOME MORE CODE TO NORMALIZE THIS... this is not enough.
inputDayEnum = inputDayEnum.toUpperCase();
const reqIndex = daysOfTheWeek.indexOf(inputDayEnum);
return datesOfTheWeek[reqIndex];
}
Upvotes: 1
Reputation: 874
I made it this far but for some reason Friday jumps to August 2 instead of July 2. Very weird. I built this based off of an answer from, where they show you how to determine the Monday of the current week.
EDIT: The reason the dates were giving inconsistent input was because I was not applying leap year and daylight savings scenarios.
Source: Leap Year/Daylight savings Snippet
console.log(CompareDate());
function CompareDate() {
var currentDate = new Date();
var daysArr = ["MON", "TUES", "WED", "THURS", "FRI"];
var datesArr = getMonday(new Date());
var selectedDay = $('label[for=' +$('[id*=_WRAPPER]:has(.npc-time) :radio[id]:checked').attr('id') + ']').text().split('~')[0];
var selectedHour = $('label[for=' +$('[id*=_WRAPPER]:has(.npc-time) :radio[id]:checked').attr('id') + ']').text().split('~')[1].split(':')[0];
var selectedMinute = $('label[for=' +$('[id*=_WRAPPER]:has(.npc-time) :radio[id]:checked').attr('id') + ']').text().split('~')[1].split(':')[1];
var chosenDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), datesArr[$.inArray(selectedDay, daysArr)].getDate(), selectedHour, selectedMinute, 00);
console.log("Chosen date: " + chosenDate);
console.log("Current date: " + currentDate);
//Note: 04 is month i.e. May
if (chosenDate < currentDate) {
//AlertMessage();
console.log("Day/time selected is not valid because it is in the past now.");
return false;
} else {
return true;
}
} //CompareDate
//Determine the DATE of the Monday of the current week and then build off of that.
function getMonday(d) {
d = new Date();
var day = d.getDay(),
mon = d.getDate() - day + (day == 0 ? -6:1), // adjust when day is sunday,
realMon = new Date(d.setDate(mon));
tues = new Date(realMon.getTime() + (24 * 60 * 60 * 1000)),
wed = new Date(tues.getTime() + (24 * 60 * 60 * 1000)),
thurs = new Date(wed.getTime() + (24 * 60 * 60 * 1000)),
fri = new Date(thurs.getTime() + (24 * 60 * 60 * 1000)),
daysArrTest = [realMon, tues, wed, thurs, fri];
return daysArrTest;
} //getMonday
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Q26_WRAPPER"><span class='npc-time'></span>
<input type="radio" name="Q26" value="18" id="Q26_18" role="radio" aria-checked="true" checked="checked" class="checked"><label for="Q26_18" class="choice-text">MON~13:45<a class="groupx018"></a></label></div>
Upvotes: 0
Reputation: 147363
If your concept of "current week" is the Sunday to Saturday that contains the current date, then you can get the date for any day of the week using:
// Return date for specified day of week
// Week is Sunday to Saturday
function getWeekdayDate(dayName, date = new Date()) {
// dayName must be a string
if (typeof dayName != 'string') return;
// Get day number in week
let idx = ['su', 'mo', 'tu','we', 'th',
'fr', 'sa'].indexOf(dayName.toLowerCase().trim().substr(0,2));
// Check for invalid day name
if (typeof idx != 'number') return;
// Return day in month (miht
let d = new Date(date);
d.setDate(d.getDate() - d.getDay() + idx);
return d.getDate();
}
// Current week days - ECMAScript day numbering
['sunday', 'Monday', 'TUE',' wednesday', 'th','fr', 'sa'].forEach(
day => console.log(getWeekdayDate(day))
);
However, I think you want the function to return a Date object, as in the week of 28 Jun 2021 Monday is 28 and Friday is 2 (July) so just comparing the day number isn't sufficient.
What you likely want to do is set the current date to midnight at the start of the day (00:00:00) and compare to the selected day of the week at midnight and see whether it's greater, lesser or equal. There are plenty of questions about comparing dates.
// Return date for specified day of week
// Week is Sunday to Saturday
function getWeekdayDate(dayName, date = new Date()) {
if (typeof dayName != 'string') return;
let idx = ['su', 'mo', 'tu','we', 'th',
'fr', 'sa'].indexOf(dayName.toLowerCase().trim().substr(0,2));
if (typeof idx != 'number') return;
let d = new Date(date);
d.setHours(0,0,0,0);
d.setDate(d.getDate() - d.getDay() + idx);
return d;
}
// Current week days - ECMAScript day numbering
['sunday', 'Monday', 'TUE',' wednesday', 'th','fr', 'sa'].forEach( day => {
let d = getWeekdayDate(day);
let now = new Date();
now.setHours(0,0,0,0);
let sense = now < d? 'in the future' :
now > d? 'in the past' :
'today';
console.log(d.toLocaleString('default',{weekday:'long'}) +
' is ' + sense + '.');
}
);
Upvotes: 1