Mar*_*ick 3 jquery datetime momentjs
我在var中存储了两个日期(由日期选择器创建).要格式化这些我使用moment.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 + "";
});
Run Code Online (Sandbox Code Playgroud)
我无法开始from.diff(to, 'days')工作并将其存储在变量中.我试着把它设置为:
var days = from.diff(to, 'days');
Run Code Online (Sandbox Code Playgroud)
如何在var中存储这些天数之间的差异days?我感谢任何建议.
除此之外.diff(),您还可以使用片刻 duration:http://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');
});Run Code Online (Sandbox Code Playgroud)
<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' />
<button id="btn">Submit</button><hr />
<p id="result"></p>Run Code Online (Sandbox Code Playgroud)
正如我在您的代码中看到的,您有这样的评论:
Run Code Online (Sandbox Code Playgroud)// I can format the "from" var the way I want
不可以.您无法按照自己的方式格式化日期.您必须使用您要解析的日期所在的格式.在我的示例中,因为我使用的是HTML5日期,所以返回的日期采用yyyy-mm-dd格式,因此使用该格式.在您的情况下,确定文本框返回日期的格式,并使用该格式.
如果您确定返回的日期是标准格式,您也可以完全省略格式.