简体   繁体   中英

Set default date for bootstrap datepicker

I am trying to open the bootstrap datepicker on the date stored in the var startDate .

The code below is not working as the default date format for the datepicker is mm/dd/yy. startDate is in the format dd/mm/yy.

<script type="text/javascript" >
    function toggle_dp() {
        $("#myModal").modal("show");
        $("#datepicker").datepicker({
          dateFormat: 'dd/mm/yy',
          changeMonth: true,
          changeYear: true,
          defaultDate: new Date('{{ startDate }}')
        });
        $("#datepicker").datepicker( "option", "dateFormat", "dd-mm-yy" );
    }
</script>

For example, if the startDate is 05/03/2018 (5th March), the datepicker will open with default date 03/05/2018 (3rd May).

Use formate: instead of dateFormat:

<script type="text/javascript" >
    function toggle_dp() {
        $("#myModal").modal("show");
        $("#datepicker").datepicker({
          format: 'dd/mm/yy',
          changeMonth: true,
          changeYear: true,
          defaultDate: new Date(toMMDDYYYY(startDate))
        });

    }

function toMMDDYYYY(date) {
            var datePart = date.split("/");
            var MMDDYYYY = [datePart[1], datePart[0],datePart[2]].join('/');
            return MMDDYYYY
        }
</script>

You have written the wrong syntax for format . Just replace dateFormat with format in your script code like below

More help on Bootstrap Date-picker Format

<script type="text/javascript">
  function toggle_dp() {
    $("#myModal").modal("show");
    $("#datepicker").datepicker({
      format: 'dd/mm/yy',
      changeMonth: true,
      changeYear: true,
      defaultDate: new Date('{{ startDate }}')
    });
    $("#datepicker").datepicker("option", "format", "dd-mm-yy");
  }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM