如何用jquery比较两个日期

时间:2020-12-31 14:16:16

the 1 st one which get using the id has format

使用id的第1个元素有格式。

var checkindate = $('#check-in').text();

28-07-2011

then i get the current date using

然后我得到当前日期使用

var now = new Date();

and it has the format

它有格式

Wed Jul 20 2011 19:09:46 GMT+0530 (IST)

i want to get the date difference from these two dates . in this case it is 8 . i searched a lot and could not find an answer , please help....... :'(

我想从这两个日期中得到日期差异。这里是8。我搜索了很多,找不到答案,请帮助我……:'(

2 个解决方案

#1


5  

You can parse the initial date, feed it to a date object, substract it with the current time to get a millisecond difference, and then divide it by the number of milliseconds in a day.

您可以解析初始日期,将其提供给日期对象,用当前时间对其进行分段,以获得毫秒级的差异,然后除以一天的毫秒数。

var checkindatestr = "28-07-2011";
var dateParts = checkindatestr.split("-");

var checkindate = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
var now = new Date();
var difference = now - checkindate;
var days = difference / (1000*60*60*24);

alert(days);

At the time of writing this gives -7.5. It's a negative number because the date is in the future. If you want a positive number, just swap the variables in the substraction. If you want a round number, just use Math.round.

写这篇文章的时候得到-7。5。这是个负数,因为日期在将来。如果你想要一个正数,只需在减法中交换变量。如果你想要整数,就用math。round。

#2


3  

You can parse your first date as described in this thread: Parse DateTime string in JavaScript

您可以按照此线程中的描述解析第一次日期:在JavaScript中解析DateTime字符串。

var strDate = "28-07-2011";
var dateParts = strDate.split("-");

var date = new Date(dateParts[2], (dateParts[1] - 1) ,dateParts[0]);

And then compare the two dates as asked here: Compare two dates with JavaScript

然后比较这两个日期:比较两个日期和JavaScript

#1


5  

You can parse the initial date, feed it to a date object, substract it with the current time to get a millisecond difference, and then divide it by the number of milliseconds in a day.

您可以解析初始日期,将其提供给日期对象,用当前时间对其进行分段,以获得毫秒级的差异,然后除以一天的毫秒数。

var checkindatestr = "28-07-2011";
var dateParts = checkindatestr.split("-");

var checkindate = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
var now = new Date();
var difference = now - checkindate;
var days = difference / (1000*60*60*24);

alert(days);

At the time of writing this gives -7.5. It's a negative number because the date is in the future. If you want a positive number, just swap the variables in the substraction. If you want a round number, just use Math.round.

写这篇文章的时候得到-7。5。这是个负数,因为日期在将来。如果你想要一个正数,只需在减法中交换变量。如果你想要整数,就用math。round。

#2


3  

You can parse your first date as described in this thread: Parse DateTime string in JavaScript

您可以按照此线程中的描述解析第一次日期:在JavaScript中解析DateTime字符串。

var strDate = "28-07-2011";
var dateParts = strDate.split("-");

var date = new Date(dateParts[2], (dateParts[1] - 1) ,dateParts[0]);

And then compare the two dates as asked here: Compare two dates with JavaScript

然后比较这两个日期:比较两个日期和JavaScript