gpt4 book ai didi

javascript - 无法比较星期五日期 JavaScript

转载 作者:行者123 更新时间:2023-11-27 23:54:07 26 4
gpt4 key购买 nike

您好,我有一个场景,我需要获取过去两周内售出的书籍数量。我正在使用 Javascript 来实现这一点。直到今天一切都运转良好。当日期是星期五时,比较失败。下面是示例。

   //Function to get Monday of thisweek,last week and last to last week.
function GetMonday(mday) {
var today, todayNumber, mondayNumber, monday;
today = new Date();
todayNumber = today.getDay();
mondayNumber = mday - todayNumber;
return new Date(today.getFullYear(), today.getMonth(), today.getDate() + mondayNumber).toDateString();
}


var currDate = new Date().toDateString(); // gets todays date
var currwkDate = GetMonday(1); //Gets this week Monday's Date
var lastwkDate = GetMonday(-6); //Gets last week Monday's Date
var twowkDate = GetMonday(-13); //Gets Last to last week Monday's Date

var BillDate=new Date("09/04/2015").toDateString(); // Friday (04 Sep)
if (currDate == BillDate) {
alert("equal");
}
if (BillDate > currwkDate) {
alert("this week");
}
if (BillDate > lastwkDate) {
alert("last week");
}
if (BillDate > twowkDate) {
alert("two week")
}

理想情况下,上面的代码应该得到三个警报框(本周、上周、两周),但它甚至不给出单个警报。

如果我编辑上面的代码并将 BillDate 设置为非星期五的任何其他日期,例如,相同的代码将正常工作

   var BillDate= new Date("09/03/2015").toDateString(); //Thursday 03-Sep

我不确定问题是什么,请帮忙!!!!!!

最佳答案

您的代码实际上是在进行字符串比较而不是日期比较。失败的原因是 M从周一开始小于T , W ,和S ,但不是F .

这使得 BillDate > currwkDate如果是星期五,则为假。自 F < M 。解决方法是比较日期(删除 toDateString 的使用):

   //Function to get Monday of thisweek,last week and last to last week.
function GetMonday(mday) {
var today, todayNumber, mondayNumber, monday;
today = new Date();
todayNumber = today.getDay();
mondayNumber = mday - todayNumber;
return new Date(today.getFullYear(), today.getMonth(), today.getDate() + mondayNumber);
}


var currDate = new Date(); // gets todays date
var currwkDate = GetMonday(1); //Gets this week Monday's Date
var lastwkDate = GetMonday(-6); //Gets last week Monday's Date
var twowkDate = GetMonday(-13); //Gets Last to last week Monday's Date

var BillDate=new Date("09/04/2015"); // Friday (04 Sep)
if (currDate.getYear() == BillDate.getYear() && currDate.getMonth() == BillDate.getMonth() && currDate.getDate() == BillDate.getDate()) {
alert("equal");
}
if (BillDate > currwkDate) {
alert("this week");
}
if (BillDate > lastwkDate) {
alert("last week");
}
if (BillDate > twowkDate) {
alert("two week")
}

编辑:第一次检查日期是否相等也需要修改为仅检查年、月和日期(忽略小时/等)。

关于javascript - 无法比较星期五日期 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32411276/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com