Mwangi Murimi
Mwangi Murimi

Reputation: 13

How do you put a variable date on javascript?

I've been trying to use the input data from my HTML to create a date object but no mater what I tweak, it either shows invalid date, or gives today's date. Any help on how I can solve this? Or corrections on what I may be doing wrong? Thanks. Here's my code below.

    <input type="date" id="date">
    <script>
    var date = document.getElementById("date").value();
    var d = new Date(d);
    </script>

Upvotes: 1

Views: 1009

Answers (3)

Hans Fugers
Hans Fugers

Reputation: 1

You can try the following:

<!DOCTYPE html>
<html>
<head>
<title>Date experiment</title>

<script>
function processDate(mdate){
    console.log(mdate); 
    }
</script>
</head>
<body>
<p>This is a paragraph.</p>
<form>
  Date : <br>
  <input type="date" id="start" name="mydate" onchange="processDate(this.value)"
       value="2019-10-20" min="2019-10-01" max="2019-12-31">
</form>
</body>
</html>

Upvotes: 0

Divyesh patel
Divyesh patel

Reputation: 997

May be helpful to you:

        function x(){
        var date = document.getElementById("date").value;
        var d = new Date(date);
        console.log(d);
        }
        
        
<input type="date" id="date">
<button onclick="x()">show</button>

Upvotes: 1

Hien Nguyen
Hien Nguyen

Reputation: 18973

You put wrong .value() change to .value.

You can use momentjs to format date YYYY-MM-DD

function check(){
var date = document.getElementById("date").value;
    var d = new moment(date, 'YYYY-MM-DD');
    console.log(d)
}

function check(){
var date = document.getElementById("date").value;
    var d = new moment(date, 'YYYY-MM-DD');
    console.log(d)
}
    <input type="date" id="date" onblur="check()">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js" integrity="sha256-4iQZ6BVL4qNKlQ27TExEhBN1HFPvAvAMbFavKKosSWQ=" crossorigin="anonymous"></script>

Upvotes: 3

Related Questions