简体   繁体   中英

Set Html5 Datepicker value from string

I can set the value to today'd date, but I can't seem to set the value based on a custom date string. I've shown in the code below the idea of what I want to do.

I have to use the string format of date that I specified below so that can't be changed, but can the format of the date string be modified?

var newDate = new Date();    
newDate = "30/03/2020 12:00:00 AM";

$('#datePickerId').val(newDate);

error:
jquery.min.js:4 The specified value "30/03/2020 12:00:00 AM" does not 
conform to the required format, "yyyy-MM-dd".

You can do this in following 2 ways. newDate1: Javascript datetime newDate2: moment js

 $(document).ready(function(){ var newDate1 = new Date(2020,03,30); console.log(newDate1); var mm = newDate1.getMonth(); var dd = newDate1.getDate(); var aa = newDate1.getFullYear() +"-" + (mm < 10? "0":"") +mm +"-" + (dd < 10? "0":"") + dd; $('#datePickerId1').val(aa); var newDate2 = moment("30/03/2020 12:00:00 AM","DD/MM/YYYY hh:mm:ss A").format("YYYY-MM-DD"); //console.log(newDate2); $('#datePickerId2').val(newDate2); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script> <h1>Show a date control:</h1> First: <input type="date" name="bday" id=datePickerId1><br/> Second: <input type="date" name="bday" id=datePickerId2>

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