I have a function called convert which take in date (20140107) and replace the 4,2,2 position with a slash / (2014/01/07)for the date to be readable on the screen I will like to also remove the slashes before I sending it to the database In summary, this is what I am trying to do take a date of this form 2014/01/07 and convert it to 20140107
below is the convert function
function convert($date)
{
$numbers_only = preg_replace("/[^\d]/", "", $date);
return preg_replace("/^1?(\d{4})(\d{2})(\d{2})$/", "$1/$2/$3", $numbers_only);
}
Thank you in advance
Just use str_replace
function convert($date)
{
str_replace("/", "", $date);
}
It would be best to use a Datetime object as a middle man for this.
Create from format would allow you to create a Datetime without using string manipulation
http://uk1.php.net/manual/en/datetime.createfromformat.php
You can then use the format function to output it in the way that you prefer.
http://uk1.php.net/manual/en/datetime.format.php
Along the lines of...
$dateObj = DateTime::createFromFormat('Y/m/d', $date);
echo $dateObj->format('Ymd');
Just use str_replace()
. Much simpler:
echo str_replace('/', '', $date);
You can use the built in PHP function str_replace()
. So just call
return str_replace('/', null, $numbers_only);
Instead of
return preg_replace("/^1?(\d{4})(\d{2})(\d{2})$/", "$1/$2/$3", $numbers_only);
$originalDate = "2014/01/07";
$newDate = date("Ymd", strtotime($originalDate));
echo $newDate;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.