converting some numbers to make them mysql date happy?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
robster
Forum Contributor
Posts: 360
Joined: Wed Jul 16, 2003 8:28 am
Location: Sunshine Coast, Australia

converting some numbers to make them mysql date happy?

Post by robster »

Hi there, I have some variables, and an example of their content may be this:

Code: Select all

$day = "1";
$month = "9";
$year = "2006"

I need to get these numbers into the mysql date format, which in this case would be "2006-09-01".

Can anyone describe what functions or tools or methods might be available to me to do this? I've had a programming break and am a bit rusty in the logic department :(

Any help GREATLY appreciated.


Rob
ntbd
Forum Newbie
Posts: 21
Joined: Wed Apr 12, 2006 6:42 am

Post by ntbd »

er $db_friendly = "$year/$month/$day"; ?

too simple? ;)
User avatar
robster
Forum Contributor
Posts: 360
Joined: Wed Jul 16, 2003 8:28 am
Location: Sunshine Coast, Australia

Post by robster »

:) thanks but not quite...
Note the preceding 0's on the required data.

ie: 1 vs 01 and 6 vs 06.


Any suggestions?


Rob
ntbd
Forum Newbie
Posts: 21
Joined: Wed Apr 12, 2006 6:42 am

Post by ntbd »

Sorry, this might be more useful.

Code: Select all

$date = "10-3-1987";
$date = preg_replace("/([0-9]+)-([0-9]+)-([0-9]+)/ie", "'\\3-'.str_pad('\\2', 2, '0', STR_PAD_LEFT).'-'.str_pad('\\1', 2, '0', STR_PAD_LEFT)", $date);
Then insert $date. It wont automaticaly pad the year though.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

Code: Select all

$date = str_pad($year, 4, '0', STR_PAD_LEFT) . '-' . str_pad($month, 2, '0', STR_PAD_LEFT) . '-' . str_pad($day, 2, '0', STR_PAD_LEFT);
User avatar
cj5
Forum Commoner
Posts: 60
Joined: Tue Jan 17, 2006 3:38 pm
Location: Long Island, NY, USA

Post by cj5 »

Go to the manual and read about sprintf()
User avatar
robster
Forum Contributor
Posts: 360
Joined: Wed Jul 16, 2003 8:28 am
Location: Sunshine Coast, Australia

Post by robster »

Thank you all so much... wow, bit to re-learn :)


Rob
Post Reply