Home > front end >  DateTime parsing results in "Failed to parse time string" error
DateTime parsing results in "Failed to parse time string" error

Time:07-07

Code:

<?php 
    $date =new \DateTime($_GET['date'],new \DateTimeZone('Africa/Maputo')); ?>

Error:

vFatal error: Uncaught Exception: DateTime::__construct(): Failed to parse time string (2022-06-14T06:00:00 02:00) at position 20 (0): Double time specification in C:\xampp2\htdocs\fullcalendar\views\user\add.php:3 Stack trace: #0 C:\xampp2\htdocs\fullcalendar\views\user\add.php(3): DateTime->__construct('2022-06-14T06:0...', Object(DateTimeZone)) #1 {main} thrown in C:\xampp2\htdocs\fullcalendar\views\user\add.php on line 3

CodePudding user response:

  1. You have extra " 02:00" characters in your date from GET-parameter. You just have to use "2022-06-14T06:00:00" instead of "2022-06-14T06:00:00 02:00" and it will work.

  2. Remember that new DateTime might throw an Exception if date-time format is not valid.

Below are fixed code sample that will work for you in any way. Try to check and play with it: uncomment some lines and see how it goes.

<?php

$default = 'now';
$dateParam = $_GET['date'] ?? $default;
//$dateParam = '2022-06-30 00:00:00'; // correct
//$dateParam = '2022-06-14T06:00:00'; // correct (2)
//$dateParam = '2022- 06- 30'; // not correct
//$dateParam = '2022-06-14T06:00:00 02:00'; // not correct (2)

try {
    $dateTime = new \DateTime($dateParam, new \DateTimeZone('Africa/Maputo'));
} catch (\Exception $e) {
    //$dateTime = new \DateTime($default);
    die('The error: ' . $e->getMessage());
}


var_dump($dateTime);

CodePudding user response:

When I was looking at your Code There was a Error on the Code on line 2

Which is $date

If you want to Make the Date time to Africa/Maputo Then The Code has to Be like this

// Language PHP

<?php
$date = date_default_timezone_set('Africa/Maputo');

echo date('Y:m:d h:i:s')

?>

// End PHP

  • Related