tags:

views:

49

answers:

7

I'm having date 20/12/2001 in this formate . i need to convert in following formate 2001/12/20 using php .

thanks in advance

A: 
$today = date("Y/m/d");

I believe that should work... Someone correct me if I am wrong.

Inanepenguin
this is only get the date . I need to convert it anyway thanks for the response
gowri
If you have it always in the format d/m/y then you could parse the info and just rearrange. I thought you meant you were calling the date in that order, but wanted to know how to call it in a different order.
Inanepenguin
+3  A: 
$var = explode('/',$date);
$var = array_reverse($var);
$final = implode('/',$var);
Orbit
+1  A: 

If you're getting the date string from somewhere else (as opposed to generating it yourself) and need to reformat it:

$date = '20/12/2001';
preg_replace('!(\d+)/(\d+)/(\d+)!', '$3/$2/$1', $date);

If you need the date for other purposes and are running PHP >= 5.3.0:

$when = DateTime::createFromFormat('d/m/Y', $date);
$when->format('Y/m/d');
// $when can be used for all sorts of things
outis
+1  A: 

You will need to manually parse it.

  1. Split/explode text on "/".
  2. Check you have three elements.
  3. Do other basic checks that you have day in [0], month in [1] and year in [2] (that mostly means checking they're numbers and int he correct range)
  4. Put them together again.
staticsan
+2  A: 

Your safest bet

<?php
$input = '20/12/2001';
list($day, $month, $year) = explode('/',$input);
$output= "$year/$month/$day";
echo $output."\n";

Add validation as needed/desired. You input date isn't a known valid date format, so strToTime won't work.

Alternately, you could use mktime to create a date once you had the day, month, and year, and then use date to format it.

Alan Storm
A: 

You can use sscanf in order to parse and reorder the parts of the date:

$theDate = '20/12/2001';
$newDate = join(sscanf($theDate, '%3$2s/%2$2s/%1$4s'), '/');

assert($newDate == '2001/12/20');

Or, if you are using PHP 5.3, you can use the DateTime object to do the converting:

$theDate = '20/12/2001';
$date = DateTime::createFromFormat('d/m/Y', $theDate);
$newDate = $date->format('Y/m/d');

assert($newDate == '2001/12/20');
Max
A: 
$date = Date::CreateFromFormat('20/12/2001', 'd/m/Y');
$newdate = $date->format('Y/m/d');
Marc B