PHP string manipulation examples: Date Formatting and Conversion


I love string manipulation in PHP, especially if I pressured myself to complete the programming work in around 30 minutes. It really cracks my head off and a good mental exercise (better than chess or playing sudoko). Anyway in this PHP string manipulation exercises, we attempt to convert the date in the format of Apr 16, 2010 to 4/16/2010. Date Syntax: Month date,year to Month/date/year

Below is the complete PHP script with short explanation (assuming date variable used in this script is $date):

<?php
//find first space
$firstspace = strpos($date," ");

//FILTER MONTH

$month=substr($date,0,$firstspace);
//remove space in month
$month=trim($month);

//find comma
$commalocation = strpos($date,",");

//find number of characters occupied by date
$charcount=$commalocation-$firstspace;

//FILTER DAY
$day=substr($date,$firstspace,$charcount);
//remove space in day
$day=trim($day);

//FILTER YEAR
$locationforyear= $commalocation+ 1;
$year=substr($date,$locationforyear,5);
//remove space in year
$year=trim($year);

//get conversion for month

if ($month=='Jan') {
$monthconverted=1;
}
if ($month=='Feb') {
$monthconverted=2;
}
if ($month=='Mar') {
$monthconverted=3;
}
if ($month=='Apr') {
$monthconverted=4;
}
if ($month=='May') {
$monthconverted=5;
}
if ($month=='Jun') {
$monthconverted=6;
}
if ($month=='Jul') {
$monthconverted=7;
}
if ($month=='Aug') {
$monthconverted=8;
}
if ($month=='Sep') {
$monthconverted=9;
}
if ($month=='Oct') {
$monthconverted=10;
}
if ($month=='Nov') {
$monthconverted=11;
}
if ($month=='Dec') {
$monthconverted=12;
}

//Finalization of date format from Apr 16, 2010 to 4/16/2010 format

$date= $monthconverted.'/'.$day.'/'.$year;
$date=trim($date);
?>

This exercise is fairly similar to what we use in the PHP String Manipulation Functions: SUBSTR and STRPOS tutorial. I hope you will find this one helpful.



Related posts: