Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

html - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...