0

Hi I am trying to get some PHP date formatting resolved. The problem I am having is random unexpected results being returned instead of the correct date after I try and format them.

I have the date MM/DD/YY passed in as a string and I am wondering how to convert that to a YYYY/MM/DD. When it try to convert the date it is like it is staying in the same place but trying to convert the individual section so the MM (12) goes to the year YYYY (2012)


Here is the section of code I have been using to try and change the format:

$date = $_GET["datepicker"];
$arr[$i] = strftime("%Y-%m-%d", strtotime($date));

The $arr[$i] is just the array I am putting it into this shouldn't affect anything. I have also tried the following:

$arr[$i] = date("Y-m-d", strtotime($date));

Thanks,
Kieran

Kieranmv95
  • 828
  • 4
  • 14
  • 31
  • This site does have a search function : http://stackoverflow.com/questions/2487921/convert-date-format-yyyy-mm-dd-dd-mm-yyyy/2487938#2487938 – CD001 Jan 12 '15 at 15:53
  • Your problem is more a logic problem than a programming one. One question may help you solve it by yourself : ask yourself how could php recognise in what format you your `$date` variable is actually representing the date. – β.εηοιτ.βε Jan 12 '15 at 15:54

2 Answers2

3

The easiest way to get the output you need is to use the DateTime class, in particular: DateTime::createFromFormat:

$date = DateTime::createFromFormat('m/j/y', $_GET['datepicker']);
//now to get the outpu:
$arr[$i] = $date->format('Y-m-d');

There is a procedural-style alternative, too:

$date = date_create_from_format('m/j/y', $_GET['datepicker']);
//note, date_create_from_format returns an instance of DateTime
$arr[$i] = date_format($date, 'Y-m-d');//same as $date->format('Y-m-d');
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
  • I am using the procedural method because I want to keep it in the style of the rest of the application. when this gets added to sql it reads back out as `01-01-1970` – Kieranmv95 Jan 12 '15 at 16:07
  • @Kieranmv95: the return values of `DateTime::format` and `date_format` are strings, so you needn't process them after the format calls. Also ensure that the `$_GET['datepicker']` value is correct before attempting to parse it, and check the return value of `format`. On your choosing the procedural style: that's entirely down to you, provided you stick to one coding style, you're good. Be weary, though, because -like I said in the comments- `date_create_from_format` _does_ return an object – Elias Van Ootegem Jan 12 '15 at 16:11
0

You can use mktime:

$date = $_GET["datepicker"];
list($month, $day, $year) = explode('/', $date);
$timestamp = mktime(0, 0, 0, $month, $day, $year);

$output = date('Y-m-d', $timestamp)
hsz
  • 148,279
  • 62
  • 259
  • 315