sagesky36
sagesky36

Reputation: 4692

trying to get the today's date in a JS input boxc

I am unable to set the current date in an input box in JS.

I've tried the below code, but it still defaults just to "MM/DD/YYYY" as a placeholder.

How can I set the date to the current date?

HTML:

<label>Start Date:</label>
<input type="date" id="dteStartDate">

JavaScript:

var currdate = new Date();
var currdate = (currdate.getMonth() + 1) + '/' + 
                currdate.getDate() + '/' + 
                currdate.getFullYear();

$('#dteStartDate').datetimepicker({dateFormat: 'mm-dd-yy'})
                  .datetimepicker("setDate", currdate);

Upvotes: 4

Views: 117

Answers (3)

Yann Chabot
Yann Chabot

Reputation: 4869

Using the javascript Date object. If you want to format it MM/DD/YYYY, I suggest you going that way:

 function formatDate(d) {

    var dd = d.getDate()
    if ( dd < 10 ) dd = '0' + dd

    var mm = d.getMonth()+1
    if ( mm < 10 ) mm = '0' + mm

    var yy = d.getFullYear() % 100
    if ( yy < 10 ) yy = '0' + yy

    return mm+'/'+dd+'/'+yy
}

Then, you can go that way:

var now = new Date();
formattedDate = formatDate(now);

$('#dteStartDate').val(formattedDate);

Here is a good ressource for Date in javascript: http://javascript.info/tutorial/datetime-functions

Upvotes: 1

Dagriel
Dagriel

Reputation: 574

You can try this:

<input id="date" name="date">

<script type="text/javascript">
  document.getElementById('date').value = Date();
</script>

Upvotes: 1

Bruno
Bruno

Reputation: 4665

Try

$('#dteStartDate').datetimepicker({dateFormat: 'mm-dd-yy'})
              .datetimepicker("setDate", new Date());

No need to transform it into a string

Upvotes: 4

Related Questions