0

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.

2 Answers 2

3

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/

Sign up to request clarification or add additional context in comments.

Comments

-1

Fetch the value using the following :

$("#elementname").data('datepicker').getFormattedDate('YYYY-MM-DD');

1 Comment

Thanks for advise! but my problem is not fetching value. The problem is about defaultDate. Even though I set the default date but it always showing current date that I set when setting up datepicker and not showing the set date. Moreover the datepicker keep showing current date even I select other date value. By the way, I'm using React.js and consider the environment as virtual DOM. Thanks heap for your kind advise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.