用momentjs计算两个日期之间的天数

时间:2016-01-27 11:41:08

标签: jquery datetime momentjs

我在var中存储了两个日期(由日期选择器创建)。要格式化这些,我使用的是moments.js

我想计算这两个字段之间的天数,并将此数字存储在var days中。到目前为止,这是我的代码:

// When someone clicks my submit button, I create an url stored in the var url.
$(".book_submit").on('click', function(e){

  // I get the datepicker and input fields data
  var from = $('.from').val();
  var to = $('.to').val();

  // I can format the "from" var the way I want
  from  = moment(from, "DD.MM.YYYY");
  from = moment(from).format("YYYY-MM-DD");

  // I can format the "to" var the way I want
  to = moment(to, "DD.MM.YYYY");
  to = moment(to).format("YYYY-MM-DD");

  // I want to store the number between the two dates in the var "days", to place it inside my link below. I have found ".diff(to, 'days') in the moments documentation.

  //days = from.diff(to, 'days');   // =1

  var url = "https://mycustomlink&days= " + days + "";

});

我无法让from.diff(to, 'days')工作并将其存储在变量中。我试图将它设置为:

var days = from.diff(to, 'days');

如何在var days内存储这些天数之间的差异?我很感激任何建议。

2 个答案:

答案 0 :(得分:8)

.diff()外,您还可以使用时刻 durationhttp://momentjs.com/docs/#/durations/

编辑 :不知道我当时在想什么。谢谢@aedm指出来了。这里不需要持续时间,这是为了创建时间跨度。

.diff按预期工作,只需要确保使用正确的格式来解析日期。

示例小提琴:https://jsfiddle.net/abhitalks/md4jte5d/

示例代码段



$("#btn").on('click', function(e) {
	var fromDate = $('#fromDate').val(), 
  		toDate = $('#toDate').val(), 
		from, to, druation;
  
	from = moment(fromDate, 'YYYY-MM-DD'); // format in which you have the date
	to = moment(toDate, 'YYYY-MM-DD');     // format in which you have the date
  
	/* using diff */
	duration = to.diff(from, 'days')     
	
	/* show the result */
	$('#result').text(duration + ' days');
  
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
From: <input id="fromDate" type='date' />
To: <input id="toDate" type='date' />&nbsp;&nbsp;
<button id="btn">Submit</button><hr />
<p id="result"></p>
&#13;
&#13;
&#13;

正如我在您的代码中看到的,您有这样的评论:

// I can format the "from" var the way I want

没有。您无法按照 的方式格式化日期。您必须使用您要解析的日期所在的格式。在我的示例中,由于我使用的是HTML5日期,因此返回的日期采用yyyy-mm-dd格式,因此使用该格式。在您的情况下,确定文本框返回日期的格式,并使用该格式。

如果您确定返回的日期是标准格式,您也可以完全省略格式。

答案 1 :(得分:1)

要获得另一个测量单位的差异,请将该测量值作为第二个参数传递。

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1

Refer this for further

相关问题