1

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".
4
  • 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]). Commented Sep 18, 2019 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 Commented Sep 18, 2019 at 23:30
  • Possible duplicate of How to format a JavaScript date Commented Sep 18, 2019 at 23:34
  • Are you able to use a library like moment.js or fecha.js? Commented Sep 19, 2019 at 3:59

1 Answer 1

1

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>

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

Comments

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.