javascript 如何比较javascript中的两个日期时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20363764/
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
How to compare two datetime in javascript?
提问by Mhmt
I tried create markers by JSON parse from C #.I have a small problem about datetime compare in javascript.
我尝试通过 C# 中的 JSON 解析创建标记。我有一个关于 javascript 中日期时间比较的小问题。
var nowDate= new Date();
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(),nowDate.getHours(),nowDate.getMinutes()- 10);
var Time1= data2.LastRecordTime;
var image2;
var status;
if (new Date(Time1) < new Date(LastTenMin)) {
image2 = '/Images/truckOnline.png';
status = "Truck is online."+"\n"+"Last seen:"+" "+Time1,
}
else {
image2 = '/Images/truckOffline.png';
status = "Truck is offline"+"\n"+"Last seen:"+" "+Time1,
}
else is not working ! There are truckOnline markers on google map.Where is my mistake ?
否则不起作用!谷歌地图上有卡车在线标记。我的错误在哪里?
And LastRecordTime format like this in SQL : 04.12.2013 01:03:00
SQL 中的 LastRecordTime 格式如下: 04.12.2013 01:03:00
LastRecordTime=CONVERT(VARCHAR(10), [ReadTimeColumn], 104) + ' ' + CONVERT(VARCHAR(8), [ReadTimeColumn],108)
回答by bigbangtheorem
Mehmet,
穆罕默德,
Looks like you made a typo:
看起来你打错了:
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(),nowDate.getHours(),nowDate.getMinutes(),- 10);
Should be (note the comma):
应该是(注意逗号):
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(),nowDate.getHours(),nowDate.getMinutes() - 10);
Also you were trying to create a new date object from a date object, this is incorrect:
您还试图从日期对象创建一个新的日期对象,这是不正确的:
new Date(LastTenMin)
And here is a more complete solution:
这是一个更完整的解决方案:
var nowDate= new Date();
var Time1 = new Date("04/12/2013 01:03:00");
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), nowDate.getHours(), nowDate.getMinutes() - 10);
// Should return true
console.log(Time1 < LastTenMin);
// Change the year to a point in the future
Time1 = new Date("04/12/2014 01:03:00");
// Shold return false
console.log(Time1 < LastTenMin);
// So your original conditional should look like this:
if (Time1 < LastTenMin) {
image2 = '/Images/truckOnline.png';
status = "Truck is online."+"\n"+"Last seen:"+" "+Time1;
} else {
image2 = '/Images/truckOffline.png';
status = "Truck is offline"+"\n"+"Last seen:"+" "+Time1;
}
// And a more concise form:
var isOnline = !(Time1 < LastTenMin);
var image2 = isOnline ? '/Images/truckOnline.png' : '/Images/truckOffline.png';
var status = "Truck is " + (isOnline ? "Online" : "Offline") + "." + "\n" + "Last seen:" + " " + Time1
Here is the solution without comments:
这是没有评论的解决方案:
var nowDate= new Date();
var Time1 = new Date(data2.LastRecordTime);
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), nowDate.getHours(), nowDate.getMinutes() - 10);
var isOnline = !(Time1 < LastTenMin);
var image2 = isOnline ? '/Images/truckOnline.png' : '/Images/truckOffline.png';
var status = "Truck is " + (isOnline ? "Online" : "Offline") + "." + "\n" + "Last seen:" + " " + Time1
My whole solution is assuming that the string contained in data2.LastRecordTime is in the format: "MM.DD.YYYY HH:MM:SS".
我的整个解决方案是假设 data2.LastRecordTime 中包含的字符串采用以下格式:“MM.DD.YYYY HH:MM:SS”。
回答by Ivan Plenty
This is going to sound like a cop out, but I would switch to MomentJSso you get the following code:
这听起来像一个警察,但我会切换到MomentJS所以你得到以下代码:
var Time1 = moment("04/12/2013 01:03:00");
var lastTenMin = moment().subtract({minutes: 10});
if(Time1.isBefore(lastTenMin)){
image2 = '/Images/truckOnline.png';
status = "Truck is online."+"\n"+"Last seen:"+" "+Time1.local();
} else {
image2 = '/Images/truckOffline.png';
status = "Truck is offline"+"\n"+"Last seen:"+" "+Time1.local();
}
Remember, JavaScript has random off-by-one issues for the date and month (one is zero-based, the other is one-based). The problem most likely is in this line:
请记住,JavaScript 对日期和月份有随机的一对一问题(一个是从零开始的,另一个是从一开始的)。问题很可能出在这一行:
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(),nowDate.getHours(),nowDate.getMinutes()- 10);
If you switch to MomentJS, these kind of problems will disappear. I have lost many hours fighting these same issues, so I understand!
如果你切换到 MomentJS,这些问题就会消失。我已经失去了很多时间来解决这些相同的问题,所以我明白了!
P.S. Try out the calendar() formatting feature... it may be a good fit in your UI.
PS 试试 calendar() 格式化功能...它可能非常适合您的 UI。
回答by Mhmt
I solved by SQL.
我用SQL解决了。
I set a new colum for difference minute between now and ReadTime.
我为现在和 ReadTime 之间的差异分钟设置了一个新列。
DifferenceMinute=DATEDIFF(MINUTE,ReadTime,GETDATE())
if(DifferenceMinute>10)
{
bla bla
}
else
{
bla bla
}
回答by Jitender Kumar
To compare dates with time in Javascript
we need to pass them in Date
object as "yyyy/mm/dd HH:mm" format for e.g. like "2014/05/19 23:20"
. Then you can just compare them with > or < less then symbol according to your business rule. Please see given below code for more understanding.
要将日期与时间进行比较,Javascript
我们需要将它们以Date
“yyyy/mm/dd HH:mm”格式传递到对象中,例如 like "2014/05/19 23:20"
。然后您可以根据您的业务规则将它们与 > 或 < less then 符号进行比较。请参阅下面给出的代码以获取更多理解。
$(function () {
$("input#Submit").click(function () {
var startDateTime = $("input[name='StartDateTime']").val();
var endDateTime = $("input[name='EndDateTime']").val();
var splitStartDate = startDateTime.split(' ');
var splitEndDate = endDateTime.split(' ');
var startDateArray = splitStartDate[0].split('/');
var endDateArray = splitEndDate[0].split('/');
var startDateTime = new Date(startDateArray[2] + '/ ' + startDateArray[1] + '/' + startDateArray[0] + ' ' + splitStartDate[1]);
var endDateTime = new Date(endDateArray[2] + '/ ' + endDateArray[1] + '/' + endDateArray[0] + ' ' + splitEndDate[1]);
if (startDateTime > endDateTime) {
$("#Error").text('Start date should be less than end date.');
}
else {
$("#Error").text('Success');
}
});
});
You can also see a working demo here
您还可以在此处查看工作演示