0

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?

6
  • How does strtotime not work? You have a different format in your solution. Commented Feb 7, 2013 at 4:16
  • @njk d/m/Y H:m is not a valid compound date time format. Commented Feb 7, 2013 at 4:17
  • @MarcusRecck I'm confused by the date OP says he's getting which is 12/20/2012 Commented Feb 7, 2013 at 4:18
  • He says he's getting d/m/Y H:m from the 3rd party, his example code reflects that. Commented Feb 7, 2013 at 4:20
  • "12/20/2012 14:34 -> d/m/Y H:m" ? Those don't go together. It has to be either "20/12/2012" or "m/d/Y". Which is it? Commented Feb 7, 2013 at 4:46

1 Answer 1

2

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().

Sign up to request clarification or add additional context in comments.

2 Comments

The format I need is exactly what you went through, thanks. This function generates no overhead on the server? My example is clearly bad for the server
I don't know about the performance of this script, but since it's a native function, I'd assume this is the most efficient way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.