用户脚本自动填充jQuery UI Datepicker - 错误的日期格式

时间:2016-04-18 13:27:34

标签: jquery date jquery-ui datepicker

我正在尝试自动填充jQuery UI datepicker,但日期是以MM/DD/YYYY格式粘贴的。我需要以yy-mm-dd格式粘贴它。使用本机日期选择器功能时,日期将正确填充。我正在尝试使用以下方法设置日期,但每个方法都填写错误的格式。如何以yy-mm-dd格式而不是默认的MM/DD/YYYY格式正确设置日期?

该页面使用jQuery 2.1.4和jQuery UI 1.11.4。

// initialize date
var cur = new Date();

// methods I've tried
$('.selector').datepicker('setDate', cur);

$('.selector').datepicker('formatDate', 'yy-mm-dd');
$('.selector').datepicker('setDate', cur);

$('.selector').datepicker('option', 'formatDate', 'yy-mm-dd');
$('.selector').datepicker('setDate', cur);

$('.selector').datepicker('option', 'formatDate', 'yy-mm-dd');
$('.selector').datepicker('refresh');
$('.selector').datepicker('setDate', cur);

// from answers below
$('.selector').datepicker({dateFormat: 'yy-mm-dd'});
$('.selector').datepicker('setDate', cur);

// this method changes the format displayed in the field, but the form's
// validation throws an error that it is in the wrong format. focus/unfocus
// on the field manually after this sets the date back to the previous format.
$('.selector').datepicker('setDate', cur);
var s = cur.getFullYear() + '-' + (('0' + (cur.getMonth() + 1)).slice(-2)) +
        '-' + (('0' + (cur.getDate())).slice(-2));

3 个答案:

答案 0 :(得分:0)

试试这个:

$(".selector").datepicker({dateFormat: "yy-mm-dd"});

答案 1 :(得分:0)

$('.selector').datepicker({dateFormat: 'yy-mm-dd'});
var curFormatted = $.datepicker.formatDate('yy-mm-dd', cur);
$('.selector').datepicker('setDate', curFormatted);

答案 2 :(得分:0)

我觉得很傻,但网站实际上使用bootstrap-datepicker,而不是jQuery UI datepicker。我真诚地道歉。