0

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".
Fii
  • 180
  • 12
Ryn9011
  • 111
  • 1
  • 12
  • 2
    You're creating a new `Date` variable, then immediately overwriting it with a string. Either use a string in the first place, in the correct format (i.e., `var newDate = '2020-03-30;`) or set the date variable correctly (i.e., `var newDate = new Date(2020, 2, 30);` [JavaScript months are 0-based]). – Heretic Monkey Sep 18 '19 at 23:20
  • I understand that, but what I need to know is if there's a smart way to change the date format? I hard coded that date to make the example as simple as possible but in my project, I'm stuck working with that format. I don't want to get messy with substrings if I can help it – Ryn9011 Sep 18 '19 at 23:30
  • Possible duplicate of [How to format a JavaScript date](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – Heretic Monkey Sep 18 '19 at 23:34
  • Are you able to use a library like moment.js or fecha.js? – Christopher Taleck Sep 19 '19 at 03:59

1 Answers1

0

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>
Anu
  • 216
  • 1
  • 9