Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change date format in php

Tags:

php

i develop a webpage , in that i need to change the date format from 22/01/2010 to 2010-01-22 i use the following function but i am getting a warning as "Deprecated : Function ereg() is depreceted in c:\wamp\www\testpage.php on line 33" . Is there anyway to hide that error or is there any other way to change the date format ? Please help me to solve this issue . Thanks in advance .

$datedue = $_REQUEST['txtJoiningdate'];
        $r = ereg ("([0-9]{1,2})/([0-9]{1,2})/([0-9]{4})", $datedue, $redgs);
        $billdate=$redgs[3]."-".$redgs[2]."-".$redgs[1];
like image 398
Sakthivel Avatar asked Jan 10 '10 14:01

Sakthivel


2 Answers

Why not use strtotime,date and str_replace functions native to php to do the trick in one simple line?

This way you could easily change the format of the date to whatever you want easily using the many options date offers.

echo date('Y-m-d',strtotime(str_replace("/",".","22/01/2010")));

Outputs 2010-01-22

Documentation for functions used:

  • strtotime
  • date
  • str_replace
like image 142
johnnyArt Avatar answered Oct 16 '22 13:10

johnnyArt


You are using deprecated functions. Use the preg_match instead. Also the call to preg_match should be in a if test.

<?php
$datedue = '22/01/2010';
if(preg_match('@([0-9]{1,2})/([0-9]{1,2})/([0-9]{4})@', $datedue, $redgs)) {
    $billdate=$redgs[3]."-".$redgs[2]."-".$redgs[1];    
    echo $billdate; // prints  2010-01-22 
}
?>
like image 24
codaddict Avatar answered Oct 16 '22 13:10

codaddict