Reputation: 49
My problem is that when I try to save in my database a date I receive this date: 1970-01-01
This is my html code:
<input type="text" name="dob" value="<?php echo $rows['dob']; ?>" required title="The Date of Birth is required" pattern="(0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])[-](19|20)\d\d"></input>
And this my php code to get the value:
$dob = $_POST['dob'];
echo $dob.'<br>';
$dob_new = date('Y-m-d', strtotime($dob));
echo $dob_new.'<br>';
This is the result:
01-22-1984
1970-01-01
The first date is one example that a date that the user can enter and the second date is the result of the conversion!
The mystery is that sometimes this work but sometimes no... so what happen here? Any suggestion? Any error in my code?
Upvotes: 2
Views: 3845
Reputation: 219804
When you use dashes as your date separator PHP assumes European date format which is DD-MM-YYYY. Yours is MM-DD-YYYY. As a result strtotime()
thinks it has an invalid date and returns false which causes date()
to return the date you are seeing which is the Unix Epoch.
To work around it you either need to send the date in the correct format or use DateTime::createFromFormat()
to parse the date properly.
$date = DateTime::createFromFormat('m-d-Y', $_POST['dob']);
$dob_new = $date->format('Y-m-d');
Upvotes: 8