Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get date from input form within PHP

I'm trying to retrieve a date from a date input form and I just can't get it to work properly. The code I'm using now only returns an error and this date: 1970-01-01. That is not correct and I would like to know how I can approach this. This will be used later to query a database table. I want the date to be basically just a string with this format: "yyyy-mm-dd"

Code:

HTML

<form name="DateFilter" method="POST">
From:
<input type="date" name="dateFrom" value="<?php echo date('Y-m-d'); ?>" />
<br/>
To:
<input type="date" name="dateTo" value="<?php echo date('Y-m-d'); ?>" />
</form>

PHP

$new_date = date('Y-m-d', strtotime($_POST['dateFrom']));
echo $new_date;

Thanks in advance,

~ Realitiez

~~~ EDIT ~~~

Fixed Solution for anyone wondering how it's done:

HTML

<form name="Filter" method="POST">
    From:
    <input type="date" name="dateFrom" value="<?php echo date('Y-m-d'); ?>" />
    <br/>
    To:
    <input type="date" name="dateTo" value="<?php echo date('Y-m-d'); ?>" />
    <input type="submit" name="submit" value="Login"/>
</form>

PHP

$new_date = date('Y-m-d', strtotime($_POST['dateFrom']));
echo $new_date;

Special Thanks to every answer.

like image 795
Realitiez Avatar asked May 14 '15 17:05

Realitiez


1 Answers

Validate the INPUT.

$time = strtotime($_POST['dateFrom']);
if ($time) {
  $new_date = date('Y-m-d', $time);
  echo $new_date;
} else {
   echo 'Invalid Date: ' . $_POST['dateFrom'];
  // fix it.
}
like image 95
Misunderstood Avatar answered Sep 21 '22 04:09

Misunderstood