View Full Version : Reorder a string

02-14-2006, 06:33 PM
I have a string that looks like this 20061402. basically the date but they year is first for searching purposes. anyway what i need to know is how i take that string and make it look like this "02-14-2006". can this be done or is there a better way to store the date inthe db to search that i can still make look better than 20060214

02-14-2006, 06:41 PM
i'd usually store as a unix timestamp but I don't know your situation enough, here is a way to parse it:

$str = '20060214';
print $str = preg_replace('/^(\d{4})(\d{2})(\d{2})$/', '\2-\3-\1', $str);

Kid Charming
02-14-2006, 07:49 PM
When storing dates in your db, make sure you're using a proper date column type. It will store the date as yours is stored (YYYY-MM-DD). When retrieving that date, your db will have a formatting function that will allow you to have your date display however you'd like it to, much like PHP's date() function works on unix timestamps. The function will vary depending on your db (in MySQL it's DATE_FORMAT()), for example.