0

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>
Alexander Dixon
  • 837
  • 1
  • 9
  • 24
  • You need to define "current week". Depending on where you are in the world, the first day of the week might be Saturday, Sunday or Monday. And that's just with the current Gregorian calendar. – RobG Jun 29 '21 at 00:10
  • @RobG USA, Eastern standard time. The current week, day, hour and minute will always be in real time. We are checking against what day / time (hour/minute) was selected. So if we are in Tuesday, all Monday time slots we be invalid, for example. – Alexander Dixon Jun 29 '21 at 15:32

3 Answers3

1

// 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];
}

isaacdre
  • 842
  • 7
  • 10
1

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 + '.');
  }
);
RobG
  • 142,382
  • 31
  • 172
  • 209
  • this is pretty close. My answer is the exacting thing I was looking for and the project is already live. What you have is a cleaner more robust version of it. Please refine two points and I will accept your answer (submit a new answer if you like). 1.) Put it in ECMAScript 5. 2.) Do not reset the times to midnight - The whole reason for extrapolating the date number for the current week was to see where we are down to the minute in real time and prevent past dates/times from being scheduled. 3.) Make some mention of a polyfill for `.indexOf()` or use jQuery `$.inArray()`. Thank you – Alexander Dixon Jun 29 '21 at 15:19
  • 1
    @AlexanderDixon—there was no [ECMAScript 5.2](https://www.ecma-international.org/publications-and-standards/standards/ecma-262/). Polyfils for [*indexOf*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#polyfill) and [*trim*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#polyfill) are on MDN, there are other ways to achieve the same thing that are compatible with ECMA-262 ed 5.1. If you don't want to reset the time, delete the lines of code that do that. – RobG Jun 30 '21 at 00:59
0

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

Source: Get Monday 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>
Alexander Dixon
  • 837
  • 1
  • 9
  • 24