Renato
Renato

Reputation: 345

Converting dates with PHP for DATETIME

I know there are literally thousands of similar questions, but do not ask if it was not necessary.

I researched a lot and found all the solutions that make the conversion of dates with standard PHP functions, it works perfectly if the date to be converted to have a standard, not in my case.

I am getting data from a third party site that returns me a date in the following format:

12/20/2012 14:34 -> d/m/Y H:m

Note that besides the strange pattern has not seconds.

Problem is that I tried to use these solutions as standards strtotime and also some functions, but nothing solved my problem. I ended up creating the following solution:

<?php

$data = '20/12/2012 14:34';

$teste = explode('/', $data);
$teste2 = explode(' ',  $teste['2']);

$final = $teste2['0'] . '-' .$teste['1'] .'-'. $teste['0']. ' '. $teste2['1'].':00';

echo $final;

Works perfectly, but as you can see is nothing elegant. Someone with more experience might indicate a better solution?

Upvotes: 0

Views: 119

Answers (1)

hexacyanide
hexacyanide

Reputation: 91619

This is what I came up with:

$date = '20/12/2012 14:34';
$date = str_replace('/', '-', $date);
$date = strtotime($date);

$newdate = date('d-m-Y H:i:s', $date);
echo($newdate);
//returns 20-12-2012 14:34:00

I was rather confused on which formatting you were looking for, but you can switch around the date specifications inside the date() function. See here for more information on PHP date().

Upvotes: 2

Related Questions