Jump to content


Photo

Converting Dates


  • Please log in to reply
3 replies to this topic

#1 JustinK101

JustinK101
  • Members
  • PipPipPip
  • Advanced Member
  • 503 posts
  • LocationSan Diego, California, US

Posted 28 September 2006 - 10:51 PM

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.

#2 roopurt18

roopurt18
  • Staff Alumni
  • Advanced Member
  • 3,749 posts
  • LocationCalifornia, southern

Posted 28 September 2006 - 10:54 PM

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.
PHP Forms : Part I | Part II

JavaScript: Singleton

http://www.rbredlau.com

#3 JustinK101

JustinK101
  • Members
  • PipPipPip
  • Advanced Member
  • 503 posts
  • LocationSan Diego, California, US

Posted 28 September 2006 - 11:15 PM

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.

//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);
}


#4 Fehnris

Fehnris
  • Members
  • PipPipPip
  • Advanced Member
  • 48 posts

Posted 29 September 2006 - 06:42 AM

Using substr() easiest way I can think of:-

http://us3.php.net/substr

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)


$mysqldate = substr(<your old date here>, 6, 4)."-".substr(<your old date here>, 0, 2)."-".substr(<your old date here>, 3, 2);


Code below converts your mysql date format back into the old date format. (MM/DD/YYYY pressumably)


$olddateformat = substr(<your mysql date here>, 5, 2)."/".substr(<your mysql date here>, 8, 2)."/".substr(<your mysql date here>, 0, 4);






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users