[英]jQuery UI datepicker setDate and moment.js
jQueryUI datepicker 似乎不能很好地与 moment.js 一起使用
我需要我的日期选择器预设为持续 90 天,所以FromDate
应该是 90 天前, ToDate
是今天。
$('#FromDate').datepicker({
format: 'dd-M-yyyy',
todayHighlight: true,
autoclose: true,
orientation: 'auto bottom'
});
$('#ToDate').datepicker({
format: 'dd-M-yyyy',
todayHighlight: true,
autoclose: true,
orientation: 'auto bottom'
});
var todate = new moment();
var fromdate = new moment().subtract(90, "days");
$("#FromDate").datepicker("setDate", fromdate);
$("#ToDate").datepicker("setDate", todate);
这会引发错误
JavaScript runtime error: Object doesn't support property or method 'getTime'
有什么我想念的吗? 好像是格式问题?
来自 jQuery UI setDate
文档:
设置日期选择器的日期。 新日期可以是
Date
object 或当前日期格式的字符串(例如"01/26/2009"
)、从今天开始的天数(例如+7
)或一串值和句点 ("y"
代表年,"m"
代表月,"w"
代表星期,"d"
代表天,例如"+1m +7d"
),或null
以清除所选日期。
在您的代码中,您将 object 作为setDate
的参数传递,因此 jQuery 日期选择器无法管理它。 您可以使用toDate()
方法将您的时刻对象转换为本机 JavaScript dat。
这是一个现场样本:
$('#FromDate').datepicker({ format: 'dd-M-yyyy', todayHighlight: true, autoclose: true, orientation: 'auto bottom' }); $('#ToDate').datepicker({ format: 'dd-M-yyyy', todayHighlight: true, autoclose: true, orientation: 'auto bottom' }); var todate = moment(); var fromdate = moment().subtract(90, "days"); $("#FromDate").datepicker("setDate", fromdate.toDate()); $("#ToDate").datepicker("setDate", todate.toDate());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script> <link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script> <input type="text" id="FromDate"> <input type="text" id="ToDate">
我认为您使用不同的 DatePicker 作为format
、 todayHighlight
、 autoclose
和orientation
不是 jQuery UI DatePicker 的选项。
这是一个纯 jQuery UI 示例:
$(function() { $('#FromDate').datepicker({ dateFormat: 'dd-M-yy' }); $('#ToDate').datepicker({ dateFormat: 'dd-M-yy' }); $('#FromDate').datepicker("setDate", "-90d"); $('#ToDate').datepicker("setDate", "0"); });
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <div> <p>From <input type="text" id="FromDate" /> </p> <p>To <input type="text" id="ToDate" /></p> </div>
查看更多: jQuery UI API | 日期选择器 | 设置日期
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.