我正在寻找一个简单的函数,在这个函数中,我可以传递当前周的一天字符串,它会返回日历日期编号。例如,今天,6月28日星期一。如果我把一个字符串传递到函数中,比如说;MON";,它应该返回28。
来源https://www.c-sharpcorner.com/UploadFile/8911c4/how-to-compare-two-dates-using-javascript/
对于其他上下文,我的最终目标是简单地将当前日期与所选日期进行比较,看看它是否在过去。我并没有真正使用内置的日期函数,因为前提是我们总是在本周、本月和本年。所以所有这些都已经被考虑在内了。
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>
如果您的"当前周";是包含当前日期的周日至周六,然后您可以使用获取一周中任何一天的日期
// 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))
);
然而,我认为您希望函数返回Date对象,因为在2021年6月28日的一周中,星期一是28,星期五是2(7月(,所以仅仅比较日期是不够的。
您可能想做的是将当前日期设置为一天开始时的午夜(00:00:00(,并与一周中选定的午夜日期进行比较,看看它是大、小还是相等。关于比较日期有很多问题。
// 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 + '.');
}
);
//嗯…可能有一种更快的代码高尔夫方法。。。然而,这就是我过去处理类似问题的方式。。。
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];
}
我做到了这一点,但由于某种原因,周五跳到了8月2日,而不是7月2日。非常奇怪。我根据一个答案构建了这个,他们向你展示了如何确定本周的星期一。
编辑:日期输入不一致的原因是我没有应用闰年和夏令时场景。
来源:闰年/夏令时代码段
来源:获取星期一代码段
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>