0

I have a html form that sends a date, I set this to a variable within the php and it is outputted in this format: 01/01/2000. Edit I can't change the format in which I receive the date-it's a pre-set html file.

I need to use this variable for a SQL query on a database that dates format is like this 2000-01-01. So how can I change this format and assign it to a new variable?

So $dateOne = $_REQUEST["date_1"]; #Outputs 01/01/2000

I would like 2000-01-01.

I've read a lot on here about doing this but can only manage to get 1970-01-01 by using date('Y-m-d', strtotime($dateOne)); which I think is being reset due to strtotime?

Very new to this so sorry if I have overlooked something very simple.

  • If you used a date picker (such as jquery) you can just change the date format there and the correct format will be submitted. No conversion necessary. If you are not using a date picker, then you are likely in for a world of hurt because you can't guarantee the format. Is `01/01/2000` `mm/dd/yyyy` or `dd/mm/yyyy`? – Jonathan Kuhn Mar 23 '15 at 21:46
  • Sorry should have said this: I can't change the format in which I receive the date-it's a pre-set html file-it's coursework so should be guaranteed format (UK format) and I'll add some if statements to ensure length – Will Paull Mar 23 '15 at 21:49
  • 2
    quick and dirty: `explode()` on slash, and then join back together –  Mar 23 '15 at 21:51

1 Answers1

1

This is my quick solution to this problem.

$date = DateTime::createFromFormat('m/d/Y',$_REQUEST["date_1"])->format('Y-m-d');
Mahlstrom
  • 11
  • 2
  • Hey, sorry checked it again and it changing 31/11/1980 to 1982-07-11? Any ideas? – Will Paull Mar 23 '15 at 22:33
  • swap the `m` and `d` in the `createFromFormat` call. That is saying "read in format month/day/year and output format year-month-day". If you just swap the `m` and `d` it would make it day/month/year. – Jonathan Kuhn Mar 23 '15 at 22:36
  • That is changing 31/11/1980 to 1980-12-01. And the code is: `DateTime::createFromFormat('d/m/Y',$_REQUEST["date_1"])->format('Y-m-d');` – Will Paull Mar 23 '15 at 22:42
  • Ah crap-the default values for the html form are 31/11/1980-only just realised that November only has 30 days! Cheers and sorry about this – Will Paull Mar 23 '15 at 22:56