3

I'm using the PHP5 class "DateTime" in a website, now I need to translate the website from english to spanish but I don't know if this class can show the months and days in spanish like Febrary -> Febrero and Monday -> Lunes. Thanks for your help and comments!

1 Answers1

0

This post is an answer because I cannot comment.

Did you look into stftime?

I, personally did not have great results with it so I had to revert to manually translate the months and days. The solution below: (the yii::t() part is where the translation gets done)

function tDate($format,$date='now'){
    // make the date a DateTime Object 
    if(is_string($date)) $date = new DateTime($date);
    if(is_int($date)) $date = new DateTime(date('r',$date));
    if(!is_object($date)) return 'invalid input date';

    $monthIndex = $date->format("n"); // used as array index
    $dayIndex = $date->format("w"); // used as array index

    // we store in variables the translated format text 
    eval('$M = '.yii::t('app','array ( 1 => "Jan", "Feb", "Mar", "Apr","May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")').';');
    eval('$F = '.yii::t('app','array ( 1 => "January", "February", "March", "April","May", "June", "July", "August", "September", "October", "November",    "December")').';');
    eval('$D = '.yii::t('app','array (0 => "Mon", "Tue", "Wed", "Thu","Fri", "Sat", "Sun")').';');
    eval('$l = '.yii::t('app','array (0 => "Sunday", "Monday", "Tuesday","Wednesday", "Thursday", "Friday", "Saturday")').';');

    $format_len = strlen($format);
    $buffer = '';

    // we perform the formatting as in date(), but we use our special cases. 
    for ($i = 0; $i < $format_len; $i++){
        switch($format[$i]){
            case 'M': $buffer .= $M[$monthIndex]; break; 
            case 'F': $buffer .= $F[$monthIndex]; break;
            case 'D': $buffer .= $D[$dayIndex]; break;
            case 'l': $buffer .= $l[$dayIndex]; break;
            case '\\': $buffer .= $format[++$i]; break;
            default: $buffer.= $date->format($format[$i]);
        }
    }
    return $buffer;
 }

Basically, it is the php date() function but overloads the M, F, D and l formats (I didn't bother covering all of them).

charlespwd
  • 528
  • 4
  • 10
  • Thanks charlespwd, I was using setlocale() too with the PHP5 class "DateTime", but it always shows the date in english format. May be I need to try with stftime – Jesus Trujillo Garcia Jul 31 '13 at 18:29