JustinK101 Posted September 28, 2006 Share Posted September 28, 2006 Hello, I have a variable which has the date in the following format, with leading zeros:00/00/0000I need to convert it to MySQL date format:0000-00-00What is the Easiest way? Also how do I do backwards, from MySQL date to my format? Thanks in advance. Quote Link to comment https://forums.phpfreaks.com/topic/22427-converting-dates/ Share on other sites More sharing options...
roopurt18 Posted September 28, 2006 Share Posted September 28, 2006 There's a couple methods off the top of my head.1) You can use substr to break the date down and reassemble it.2) You can use a regexp with grouping and preg_match to fill an array with the date parts and reassemble it.Or maybe there is a built in php function that does this, although I'm not aware of it's existence. Quote Link to comment https://forums.phpfreaks.com/topic/22427-converting-dates/#findComment-100544 Share on other sites More sharing options...
JustinK101 Posted September 28, 2006 Author Share Posted September 28, 2006 Just wrote these real quick, I think they should work. I hate writing functions from scratch which should already exist in PHP. :) LOL. Guess I am lazy. Hopefully others will enjoy using these instead of writing them.[code]//Takes in a date format DD/MM/YYYY and returns it as YYYY-MM-DDfunction convert_date_2_mysql_date($this_date){ $month = substr($this_date, 0, 2); $day = substr($this_date, 3, 2); $year = substr($this_date, 6, 4); return($year . "-" . $month . "-" . $day);}//Takes in a date format YYYY-MM-DD and returns it as DD/MM/YYYYfunction convert_date_2_standard_date($this_date){ $month = substr($this_date, 5, 2); $day = substr($this_date, 8, 2); $year = substr($this_date, 0, 4); return($day . "/" . $month . "/" . $year);}[/code] Quote Link to comment https://forums.phpfreaks.com/topic/22427-converting-dates/#findComment-100550 Share on other sites More sharing options...
Fehnris Posted September 29, 2006 Share Posted September 29, 2006 Using substr() easiest way I can think of:-[url=http://us3.php.net/substr]http://us3.php.net/substr[/url]Code below converts your old date format to the new mysql date format. (Im pressuming that your old date format is MM/DD/YYYY - wasnt specified in your post just 00/00/0000)[code]$mysqldate = substr(<your old date here>, 6, 4)."-".substr(<your old date here>, 0, 2)."-".substr(<your old date here>, 3, 2);[/code]Code below converts your mysql date format back into the old date format. (MM/DD/YYYY pressumably)[code]$olddateformat = substr(<your mysql date here>, 5, 2)."/".substr(<your mysql date here>, 8, 2)."/".substr(<your mysql date here>, 0, 4);[/code] Quote Link to comment https://forums.phpfreaks.com/topic/22427-converting-dates/#findComment-100695 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.