For translating the date in a website, we can have different solutions. But here, I am particularly discussing about find and replace method for date translation.
Lets say we have date in format F j, Y i.e May 7, 2019 where, Month is in English Language but what if you want to display month in Spanish or any other languages i.e. maio 7, 2019 ?
Just take care of the following steps and you can achieve the translation for Month :
1. Create an array of Months where key is the default month and value is the translation for month.
$monthNames = [ 'january' => 'enero', 'february' => 'febrero', 'march' => 'marzo' , 'april'=> 'abril' , 'may'=> 'mayo' , 'june'=> 'junio', 'july'=> 'julio', 'august' => 'agosto', 'september'=> 'septiembre' , 'october' => 'octubure', 'november'=> 'noviembre', 'december'=>'december' ];
2. Create function which replaces the default month with the translated month and returns the translated date string
function replaceWithForeignhDate($dateString, $monthNames){ /* Converts date to lower case */ $dateString = strtolower($dateString); foreach ($monthNames as $englishMonthName=>$foreignMonthName){ /* English Month is found in the $string */ if(strpos($dateString, $englishMonthName)!== false){ /* replace the english month with the spanish month */ return str_replace($englishMonthName,$foreignMonthName, $dateString); break; } } return $dateString; }
3. Call the created funtion in step 2 and achieve the translation
$dateFromStr = replaceWithForeignhDate('May 7, 2019', $monthNames); echo $dateFromStr ; // mayo 7, 2019
Views: 40