-2

I am trying to convert the date 04/03/1992 to 1992-04-03 so I can insert it into a DATE formatted SQL Table.

Below is my PHP Code. For some reason only SOMETIMES it is converted to 1970-01-01

E.g. If i try to convert 13/04/2021 this prints out as 1970-01-01

Code below -

$date = $_POST["dateOfBirth"];
$dateToTime = strtotime($date);
$DOB = date("Y-m-d", $dateToTime);

$licenseNumber = $_POST["licenseNumber"];

$licenseDate = $_POST["licenseExpiryDate"];
$licenseDateToTime = strtotime($licenseDate);
$licenseExpiryDate = date('Y-m-d', $licenseDateToTime);
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Azy Sır
  • 172
  • 2
  • 12
  • Because `13/04/2021` is `m/d/Y` and not `d/m/Y` as you expect. You know which month is the 13th? – u_mulder Jul 16 '18 at 16:07
  • `Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. If, however, the year is given in a two digit format and the separator is a dash (-), the date string is parsed as y-m-d.` - http://php.net/manual/en/function.strtotime.php – aynber Jul 16 '18 at 16:08
  • Read the docs: http://php.net/manual/en/function.strtotime.php ... "Note: Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed;" – Felippe Duarte Jul 16 '18 at 16:08
  • 1
    You seemed to understand this, since you wrote that `04/03/1992` is `1992-04-03`. So that means that `13/04/2021` would be `2021-13-04`. And unless Trump is planning calendar reforms before he leaves office, there's no month 13. – Barmar Jul 16 '18 at 16:09

1 Answers1

2

The strtotime function is sensitive to when you use forward slashes / and dashes -. Below is a quote from php.net to explain.

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

Your date is in the european format so the simplest solution would be to replace the forward slashes / with dashes - using the str_replace function.

$date = str_replace("/","-",$_POST["dateOfBirth"]); $dateToTime = strtotime($date); $DOB = date("Y-m-d", $dateToTime);

$licenseNumber = $_POST["licenseNumber"];

$licenseDate = str_replace("/","-",$_POST["licenseExpiryDate"]); $licenseDateToTime = strtotime($licenseDate); $licenseExpiryDate = date('Y-m-d', $licenseDateToTime);
WizardCoder
  • 3,353
  • 9
  • 20
  • Thanks mate - unlike the rest of these useless responses this was perfect and exactly what I was looking for. Much appreciated :) ! – Azy Sır Jul 17 '18 at 09:40