Question

I have a context in a forum settings that use date function to handle datetime string. This context accept the format string of the date function. However, the forum in the Arabic language and I want to translate the string of am and pm to another equivalent in an Arabic string such as ص and م respectively. I tried the following code to make the external (the context) date() to replace:

echo date("addslashes(date('D d M Y g:i'),'A..Z')".str_ireplace(array('pm','am'), array('م','ص'),date(' a')));

I used addslashes in hope to escape the output of the first inner date. However the output is something like that:

pm202005Sundaypm0509UTC05(20pm30UTC('Sun 20 Apr 2014 9:03'),'PM..0') م

It is just scceeded in replacing am and pm but the whole date string is missy as you see. This is a live demo of the code. I need to know does it possible to get what I need, assuming that any code will be done inside a predefined date()?

Was it helpful?

Solution

You can use a ternary operator inside the date to set a conditional format.

date($format = (date(G) > 11) ? 'h:i \ص' : 'h:i \م');

or for am/pm

date($format = (date(G) > 11) ? 'h:i \p\m' : 'h:i \a\m');

You can set the format different than h:i but this will show 05:40 pm for 17:40 or 05:40 am for 05:40. It looks for date(G) which is the hours in 0-23 format. If date(G) is greater than 11, it uses the first format, else uses the second format.

Here is a fork of your code http://ideone.com/BobelH

OTHER TIPS

There is another approach. It uses strtotime and str_replace as follows:

<?php
$dtFormat = "Y-m-d H:i:s"; //MySQL Datetime format
$curDT = date($dtFormat);
$curTime = strtotime($curDT);
$nowFormat = "Y-m-d h:i:s ";
$arrEn = array('am', 'pm');
$arrAr = array('ص', 'م');
echo date($nowFormat).str_replace($arrEn, $arrAr,date("a", $curTime));

A working demo: http://ideone.com/xfECCD

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top