How to return today input type date?

Asked

Viewed 5,727 times

2

I’m trying to fill in an input field with type="date" with the date of the day the form is being completed.

I tried the following code in PHP:

function getDatetimeNow() {
    $tz_object = new DateTimeZone('Brazil/East');
    $datetime = new DateTime();
    $datetime->setTimezone($tz_object);
    return $datetime->format('Y-m-d ');
}

In HTML I did the following:

<input name="name_01" id="id_01" type="date" value="<?php echo getDatetimeNow() ?>" />

Did not print anything, but I also tried by Javascript:

now = new Date; 
yr = now.getFullYear();
mt = now.getMonth();
dy = now.getDay();  
document.getElementById('id_01').innerHTML= yr+"-"+mt+"-"+dy;

Does anyone have any idea how to bring the field filled?

1 answer

3


With php, you can do so:

date_default_timezone_set('America/Sao_Paulo');
...
<input name="name_01" id="id_01" type="date" value="<?php echo date('Y-m-d'); ?>" />

DEMONSTRATION

Javascript-enabled:

var today = new Date();
var dy = today.getDate();
var mt = today.getMonth()+1;
var yr = today.getFullYear();
document.getElementById('id_01').value= yr+"-"+mt+"-"+dy;
<input name="name_01" id="id_01" type="text" />

Browser other questions tagged

You are not signed in. Login or sign up in order to post.