• Displaying PHP date format in right manner using JText and JDate

    Working with dates is always a challenging task specially because of the timezone compatibility. Fortunately Joomla provides good enough APIs to deal with dates. You can simply display a date in user locale/timezone using below code:

    JHtml::date($strdate, 'Y-m-d H:i:s');

    That's pretty good stuff in just a line of code. Now what happens if I would like to display the date in the following format and I would like to have the format string to be in a language file (obviously as I can translate static string such as "at" below):

    September 11 at 8:20pm

    Guess you think its pretty easy, just replace the format string.

    JHtml::date($strdate, JText::_('COM_MYCOMPONENT_FULL_DATE_FORMAT'));
    Language String: COM_MYCOMPONENT_FULL_DATE_FORMAT="F j \a\t g:i a"

    Unfortunately that doesn't work. Even through, I have escaped the characters a and t, it will not display t as \t is the escape sequence for a tab. It will display as

    September 11 a 8:20pm


    So you need to use double slash to escape it properly (\\t).  If you think, this will work, you are wrong again. The catch is JText will by default interpret backslashes and substitute appropriate characters. So the solution to get this work is force JText not to interpret backslashes by passing the third (optional) parameter as false.

    JHtml::date($strdate, JText::_('COM_MYCOMPONENT_FULL_DATE_FORMAT', false, false));

    Hope this help someone.