Jump to content

Archived

This topic is now archived and is closed to further replies.

JustinK101

Converting Dates

Recommended Posts

Hello, I have a variable which has the date in the following format, with leading zeros:

00/00/0000

I need to convert it to MySQL date format:

0000-00-00

What is the Easiest way? Also how do I do backwards, from MySQL date to my format? Thanks in advance.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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-DD
function 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/YYYY
function 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]

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.