Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String conversion to datetime return incorrect date

Tags:

php

datetime

I'm trying to convert these two dates to DateTime: 16/09/2019 15:00:00 - 21/09/2019 09:00:00

but I got an incorrect DateTime for both dates:

$duration = "16/09/2019 15:00:00 - 21/09/2019 09:00:00";
$duration = explode('-', $duration);
            
$start = strtotime($duration[0]);
$end = strtotime($duration[1]);
echo date('d/M/Y H:i:s', $start);
echo date('d/M/Y H:i:s', $end);

result:

31/Dec/1969 16:00:00

31/Dec/1969 16:00:00

like image 419
sfarzoso Avatar asked Feb 04 '26 09:02

sfarzoso


2 Answers

First, you need to set dates like dd-mm-yyyy Second, use delimiter for explode as like " - "

        $duration = "16-09-2019 15:00:00 - 21-09-2019 09:00:00";
        $duration = explode(' - ', $duration);

        $start = strtotime($duration[0]);
        $end = strtotime($duration[1]);
        echo date('d/M/Y H:i:s', $start);
        echo date('d/M/Y H:i:s', $end);
like image 184
sportakal Avatar answered Feb 05 '26 21:02

sportakal


Datetime createformatformat

For example


$date = date_create_from_format('j-M-Y', '15-Feb-2009');
echo date_format($date, 'Y-m-d');

Output

2009-02-15

Your answer

$duration = "16/09/2019 15:00:00 - 21/09/2019 09:00:00";
$duration = explode(' - ', $duration);



$date = date_create_from_format('d/m/Y:H:i:s', $duration[0]);
echo $date->getTimestamp();

$date = date_create_from_format('d/m/Y:H:i:s', $duration[1]);
echo $date->getTimestamp();

like image 26
dılo sürücü Avatar answered Feb 05 '26 23:02

dılo sürücü