Create custom date format

58 views Asked by At

I want to create my own DateTime format. I've tried the next:

function getSpanishDate(\DateTime $date)
{
    $day = date('d', $date); 
    $month = date('n', $date); 
    $year = date('Y', $date); 
    switch($month)
    {
        case 1:
            $newMonth = 'Enero';
            break;
        case 2:
            $newMonth = 'Febrero';
            break;
        case 3:
            $newMonth = 'Marzo';
            break;
        case 4:
            $newMonth = 'Abril';
            break;
        case 5:
            $newMonth = 'Mayo';
            break;
        case 6:
            $newMonth = 'Junio';
            break;
        case 7:
            $newMonth = 'Julio';
            break;
        case 8:
            $newMonth = 'Agosto';
            break;
        case 9:
            $newMonth = 'Septiembre';
            break;
        case 10:
            $newMonth = 'Octubre';
            break;
        case 11:
            $newMonth = 'Noviembre';
            break;
        case 12:
            $newMonth = 'Diciembre';
            break;                  
    }

    return $day . ' de ' . $newMonth . ' de ' . $year;
} 

but something is wrong with the $date format, because I'm getting this warning:

Warning: date() expects parameter 2 to be long, object given

So I should convert the DateTime object into a long, but how?

2

There are 2 answers

1
Marc B On BEST ANSWER

Don't both converting. You've already got a DateTime object, just its own already-provided formatting method: http://php.net/manual/en/datetime.format.php

$day = date('d', $date); // your bad version
$day = $date->format('d'); // use this instead.
0
Nathan Dawson On

You're using date so $date should be a UNIX timestamp rather than an object (DateTime).

http://php.net/manual/en/function.date.php