javascript 比较日月和年

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8714112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:19:46  来源:igfitidea点击:

Compare day month and year

javascriptdatecomparison

提问by tt0686

Good afternoon in my timezone.

在我的时区下午好。

I want to compare two dates , one of them is inserted by the user and the other is the present day. Snippet of code :

我想比较两个日期,其中一个是用户插入的,另一个是当前日期。代码片段:

    var dateString = "2012-01-03"
    var date = new Date(dateString);
    date < new Date() ? true : false;

This returns true, i think under the hood both Date objects are transformed to milliseconds and then compared , and if it is this way the "Today" object is bigger because of the hours and minutes.So what i want to do is compare dates just by the day month and year.What is the best approach ? Create a new Date object and then reset the hours minutes and milliseconds to zero before the comparison? Or extract the day the month and year from both dates object and make the comparison ? Is there any better approach ?

这返回 true,我认为在引擎盖下两个 Date 对象都转换为毫秒然后进行比较,如果是这种方式,“今天”对象会因小时和分钟而变大。所以我想做的只是比较日期按天、月和年。最好的方法是什么?创建一个新的 Date 对象,然后在比较之前将小时分和毫秒重置为零?或者从两个日期对象中提取月份和年份的日期并进行比较?有没有更好的方法?

Thanks in advance With the best regards. Happy new year

提前致谢 最好的问候。新年快乐

回答by epascarello

Set the time portion of your created date to zeros.

将创建日期的时间部分设置为零

var d = new Date();
d.setHours(0,0,0,0);

回答by Crayon Violent

Since it's in yyyy-mm-dd format, you can just build the current yyyy-mm-dd from date object and do a regular string comparison:

由于它是 yyyy-mm-dd 格式,您可以从日期对象构建当前的 yyyy-mm-dd 并进行常规字符串比较:

var currentDate = new Date();
var year = currentDate.getFullYear();
var month = currentDate.getMonth()+1;
if (month < 10) month = "0" + month;
var day = currentDate.getDate();
if (day < 10) day = "0" + day;
currentDate = year + "-" + month + "-" + day;

var dateString = "2012-01-03"
var compareDates =  dateString < currentDate ? true : false;
document.write(compareDates);

回答by Divyanshu Jimmy

A production-ready example based on top of Accepted Answer

基于已接受答案的生产就绪示例

  1. Add the following function to your Javascript

    Date.prototype.removeTimeFromDate = function () { var newDate = new Date(this); newDate.setHours(0, 0, 0, 0); return newDate; }

  2. Invoke it whenever you wish to compare

    firstDate.removeTimeFromDate() < secondDate.removeTimeFromDate()

  1. 将以下函数添加到您的 Javascript

    Date.prototype.removeTimeFromDate = function () { var newDate = new Date(this); newDate.setHours(0, 0, 0, 0); 返回新日期;}

  2. 每当您想比较时调用它

    firstDate.removeTimeFromDate() < secondDate.removeTimeFromDate()