1
resposta

PHP Fatal error: Double timezone specification

Olá, estou com o seguinte na execução do código de lista-alunos.php.

PHP Fatal error: Uncaught Exception: Failed to parse time string (UTC-10-15) at position 6 (-): Double timezone specification in C:\Users\User\Documents\estudo\PHP e PDO\lista-alunos.php:19 Stack trace:

#0 C:\Users\User\Documents\estudo\PHP e PDO\lista-alunos.php(19): DateTimeImmutable->__construct('UTC-10-15')#1 {main} thrown in C:\Users\User\Documents\estudo\PHP e PDO\lista-alunos.php on line 19

Segue abaixo o código dos meus arquivos:

projeto-inicial.php

<?php

use Alura\Pdo\Domain\Model\Student;

require_once 'vendor/autoload.php';

$student = new Student(
    null,
    'Vinicius Dias',
    new \DateTimeImmutable('1997-10-15')
);

echo $student->age();

lista-alunos.php

<?php

use Alura\Pdo\Domain\Model\Student;

require_once 'vendor/autoload.php';

$databasePath = __DIR__ . '/banco.sqlite';
$pdo = new PDO('sqlite:' . $databasePath);

$statement = $pdo->query('SELECT * FROM students;');
$studentDataList = $statement->fetchAll(fetch_style: PDO::FETCH_ASSOC);
$studentList = [];

foreach ($studentDataList as $studentData){

    $studentList[] = new Student(
        $studentData['id'],
        $studentData['name'],
        new \DateTimeImmutable($studentData['birth_date'])
    );

}

var_dump($studentList);

inserir-alunos.php

<?php

use Alura\Pdo\Domain\Model\Student;

require_once 'vendor/autoload.php';

$databasePath = __DIR__ .'/banco.sqlite';
$pdo = new PDO('sqlite:' . $databasePath);

$student = new \Alura\Pdo\Domain\Model\Student(
    null,
    'Patrícia Freitas',
    new \DateTimeImmutable('1987-10-25'));

$sqlInsert = "INSERT INTO students (name, birth_date) VALUES (:name, :birth_date);";
$statement = $pdo->prepare($sqlInsert);
$statement->bindValue(':name', $student->name());
$statement->bindValue(':birth_date', $student->birthDate()->format('Y-m-d'));

if($statement->execute()){
    echo "Aluno incluído";
}

student.php

<?php

namespace Alura\Pdo\Domain\Model;

class Student
{
    private ?int $id;
    private string $name;
    private \DateTimeInterface $birthDate;

    public function __construct(?int $id, string $name, \DateTimeInterface $birthDate)
    {
        $this->id = $id;
        $this->name = $name;
        $this->birthDate = $birthDate;
    }

    public function id(): ?int
    {
        return $this->id;
    }

    public function name(): string
    {
        return $this->name;
    }

    public function birthDate(): \DateTimeInterface
    {
        return $this->birthDate;
    }

    public function age(): int
    {
        return $this->birthDate
            ->diff(new \DateTimeImmutable())
            ->y;
    }
}

Pesquisei aqui no fórum e em outros fóruns, mas nenhuma das respostas ajudei na resolução do erro. Gostaria de saber se alguém poderia me ajudar com esse problema.

Obrigado desde já.

1 resposta

Olá, Vinicius! Tudo bem?

Primeiramente gostaria de pedir desculpas pela demora em responder o seu tópico.

Pelo erro apresentado, parece que o problema está no arquivo "lista-alunos.php", onde ocorre a criação de um objeto DateTimeImmutable com o valor 'UTC-10-15'. O erro informa que há uma especificação duplicada de fuso horário.

Uma possível solução para esse problema é verificar se o valor do campo 'birth_date' no banco de dados está sendo armazenado corretamente.

Certifique-se de que está sendo salvo um valor válido no formato 'Y-m-d', por exemplo '1997-10-15'.

Fico no aguardo do seu retorno!

Espero ter ajudado e bons estudos!

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software