I'm using bootstrap datetimepicker in my project. And I'm facing the problem with setting the date value after my input control rendered.
At first I set up the datetimepicker as follow:
$(".date").datetimepicker({
defaultDate: moment(),
format: 'YYYY-MM-DD'
}).on('keypress paste', function (e) {
e.preventDefault();
return false;
});
And then I load the actual data date value of the control by calling below function:
function SetDate(control,date)
{
$('#'+ control).datetimepicker({
defaultDate: new Date(date)
});
}
And then the datetimepicker show only current date but it return correct date value that is not current date when I fetch the value with document.getElementById('elementname').value.
Kindly advise. Thanks.
I guess, for the options showed, that you are using http://eonasdan.github.io/bootstrap-datetimepicker
The way you are using the picker is wrong, because what you are doing is calling again the picker, better do it this way:
$('#myDatepicker').datetimepicker();
And then with your control/function (I will use a button triggering the action)
$('#set').on('click', function() {
SetDate("myDatepicker", moment().subtract(1, 'day'));
});
function SetDate(control, date) {
$('#' + control).data('DateTimePicker').defaultDate(date);
}
Where .data('DateTimePicker').defaultDate(date)
is what set the defaultDate for later.
And where moment().subtract(1, 'day'))
is taking out one day and is the parameter date
, and is not necesary to parse out again as is a moment object;
If you need to parse a string date you could use:
moment('20170202','YYYY-MM-DD')
Where first parameter is your date string. https://momentjs.com/docs/#/parsing/string-format/
Here how the options are set for the plugin http://eonasdan.github.io/bootstrap-datetimepicker/Options/