jquery - 使用moment js计算两个日期之间的天数

标签 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 中?我很感激任何建议。

最佳答案

除了.diff()之外,您还可以使用moment durations: http://momentjs.com/docs/#/durations/

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

.diff按预期工作,只是您必须确保使用正确的格式来解析日期。

fiddle 示例: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>

<小时/>

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

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

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

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

关于jquery - 使用moment js计算两个日期之间的天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35036392/

相关文章:

javascript moment.js 脚本无法正常工作

javascript - 如果单击指定类别,如何显示/隐藏元数据框

javascript - Jquery图像 slider 图像下降并淡出

javascript - 开始将幻灯片切换为隐藏状态,直到获得焦点

javascript - 每年倒数一天(并找到当年那一天的日期)

c# - DateTime 列可为空时 Entity Framework 种子方法 DateTime 错误

javascript - Momentjs 日期验证

javascript - 如何在 Karma 中配置 System.js 以测试依赖于 moment.js 的代码

javascript - 如何使用cropper.js对图像进行裁剪?

c# - 如何使用 Dateformat ISO 8601 创建 .NET CultureInfo?