Bootstrap 日期选择器 + momentJS - Firefox "Invalid date"

Bootstrap datepicker + momentJS - Firefox "Invalid date"

我将 bootstrap 日期选择器与 moment.js 一起使用。

同样的方法在 Chrome 浏览器上工作正常。在 Firefox 上,它显示 Invalid date.

如果我将 format 更改为 dateFormat,它可以在 Firefox 中运行。它将日期值更改为 MM/DD/YYYY 格式。 但是,我需要在输入字段中显示 dd-MM-YYYY 格式。

请告诉我我在导致 Firefox 无法工作的代码中遗漏了什么

这是我的 javascript 代码:

JS:

$('.pickerdate').datepicker({
   startDate: today,
   format: 'dd-mmm-yyyy',
   orientation: 'bottom',
   autoclose: true,
   endDate: "+1y"
});

var $returnDate = moment($('.pickerdate').val()).format('YYYYMMDDhhmm');

你在 firefox 上得到 Invalid date 是因为你试图解析一个不是 ISO 8601 格式的字符串。正如 momentjs parsing docs 所说:

Warning: Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.

For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.

所以你必须使用moment(String, String);。在你的情况下:

moment($('.pickerdate').val(), 'DD-MM-YYYY')

无论如何请注意,您可以使用 getDate 方法来获取日期选择器的值。正如文档所述,它

Returns a localized date object representing the internal date object of the first datepicker in the selection


这里是一个工作示例,展示了如何使用日期选择器的 getDate 和时刻解析格式从选择器获取日期(并将其打印到带有时刻的自定义格式控制台)。我建议使用 getDate 版本。

var today = moment().toDate();
$('.pickerdate').datepicker({
   startDate: today,
   format: 'dd-M-yyyy',
   orientation: 'bottom',
   autoclose: true,
   endDate: "+1y"
});

$('#btn1').click(function(){
  var date = $('.pickerdate').datepicker('getDate');
  if( !date ) return;
  var $returnDate = moment(date).format('YYYYMMDDhhmm');
  console.log($returnDate);
});
$('#btn2').click(function(){
  var val = $('.pickerdate').val();
  if( !val ) return;
  var $returnDate = moment(val, 'DD-MMM-YYYY').format('YYYYMMDDhhmm');
  console.log($returnDate);
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker3.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>

<input type="text" class="form-control pickerdate">
<button id="btn1" type="button" class="btn btn-primary">Get date picker</button>
<button id="btn2" type="button" class="btn btn-primary">Get date moment</button>


请注意 bootstrap datepicker 和 momentjs 使用不同的格式标记。 我的示例使用 2 位数的月份编号, 如果您需要使用缩写和完整的月份名称,请使用: