Javascript 如何比较javascript中的两个字符串日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14781153/
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-08-24 17:53:50  来源:igfitidea点击:

how to compare two string dates in javascript?

javascriptdate

提问by GLP

I have two string dates in the format of m/d/yyyy. For example, “11/1/2012”, “1/2/2013”. I am writing a function in JavaScript to compare two string dates. The signature of my function is bool isLater(string1, string2),if the date passed by string1 is later than the date passed by string2, it will return true, otherwise false. So, isLater(“1/2/2013”, “11/1/2012”) should return true. How do I write a JavaScript function for this?

我有两个格式为 m/d/yyyy 的字符串日期。例如,“11/1/2012”、“1/2/2013”​​。我正在用 JavaScript 编写一个函数来比较两个字符串日期。我的函数的签名是 bool isLater(string1, string2),如果string1传递的日期晚于string2传递的日期,则返回true,否则返回false。因此, isLater(“1/2/2013”​​, “11/1/2012”) 应该返回 true。我如何为此编写 JavaScript 函数?

回答by Garry

var d1 = Date.parse("2012-11-01");
var d2 = Date.parse("2012-11-04");
if (d1 < d2) {
    alert ("Error!");
}

Demo Jsfiddle

演示 Jsfiddle

回答by Matt Zeunert

Parse the dates and compare them as you would numbers:

解析日期并像数字一样比较它们:

function isLater(str1, str2)
{
    return new Date(str1) > new Date(str2);
}

If you need to support other date format consider a library such as date.js.

如果您需要支持其他日期格式,请考虑使用date.js等库。

回答by fuyi

You can simply compare 2 strings

您可以简单地比较 2 个字符串

function isLater(dateString1, dateString2) {
  return dateString1 > dateString2
}

Then

然后

isLater("2012-12-01", "2012-11-01")

returns true while

返回 true 而

isLater("2012-12-01", "2013-11-01")

returns false

返回假

回答by Steven Kuipers

Directly parsing a date string that is not in yyyy-mm-dd format, like in the accepted answerdoes not work. The answer by vitrandoes work but has some JQuery mixed in so I reworked it a bit.

直接解析不是 yyyy-mm-dd 格式的日期字符串,就像在接受的答案中一样不起作用。vitran的答案确实有效,但混入了一些 JQuery,因此我对其进行了一些修改。

// Takes two strings as input, format is dd/mm/yyyy
// returns true if d1 is smaller than or equal to d2

function compareDates(d1, d2){
var parts =d1.split('/');
var d1 = Number(parts[2] + parts[1] + parts[0]);
parts = d2.split('/');
var d2 = Number(parts[2] + parts[1] + parts[0]);
return d1 <= d2;
}

P.S. would have commented directly to vitran's post but I don't have the rep to do that.

PS 会直接评论 vitran 的帖子,但我没有代表这样做。

回答by vitran

If your date is not in format standar yyyy-mm-dd (2017-02-06) for example 20/06/2016. You can use this code

如果您的日期不是标准格式 yyyy-mm-dd (2017-02-06),例如 20/06/2016。您可以使用此代码

var parts ='01/07/2016'.val().split('/');
var d1 = Number(parts[2] + parts[1] + parts[0]);
parts ='20/06/2016'.val().split('/');
var d2 = Number(parts[2] + parts[1] + parts[0]);
return d1 > d2