2

I need a function that takes any date/time and re formats it to a different format.

e.g.

$date = "31/12/2010 15:00:00" => has a format of d/m/Y H:i:s so if i need a different format like

$returning_format = "m/d/Y H:i:s" => for America date/time

$newdate = transoform_date($current_format,$returning_format,$date); the above line should return 12/31/2010 15:00:00

NOTE: I don't need it for this format only coz i can explode it and re-arrange it, so it can accept any format and return the desired format date.

1

2 Answers 2

4

For PHP 5.3+

$newdate = DateTime::createFromFormat($current_format,$date)->format($returning_fomrat);

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

4 Comments

Most shared hosting companies allow you to use php 5.2.6 therefore is practically as good as leaving it as it is or better than as it will throw php errors
You can only foorce them to adpot 5.3 by putting pressure on them ;) Luckily 5.2.16 is the last release in 5.2
I am working for a company if i forced them for each clients I would waste a hell of alot of my time befriending the hosting company for a datetime lol not practical (yet) but +1 for exact function as described on the answer
2

strtotime — Parse about any English textual datetime description into a Unix timestamp

function transform_date($return_format, $date)
{
    return date($return_format, strtotime($date));
}

7 Comments

How does it know difference between 5-1-11 and 1-5-11?
thats wat was putting me off aswell :)
strtotime on php.net tells us: Valid formats are explained in php.net/manual/en/datetime.formats.php
Don't get me wrong, strtotime is great as long as you feed it correct formats. The question was however about parsing ANY format, as long as the format specification is given.
oki , let's say you pass that time and it doesn't work as expected , you'd use @Mchi example you'd have to know the current date format , do you know it or not ? if not then the best option would be to use this .
|

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.