Alan
Alan

Reputation: 25

Getting Total seconds from DateTime php

I want to convert the DateTime after I did a dateDiff to the queried time and the current time into seconds. How do i do that? I currently have it as hh:mm:ss.

$row = mysqli_fetch_array($sql, MYSQL_ASSOC);
$statusTime = $row['date'];

$dteStart = new DateTime($statusTime);
$dteEnd = new DateTime($currentTime);
$dteDiff = $dteStart->diff($dteEnd);
echo $dteDiff->format('%H:%I:%S');

Upvotes: 0

Views: 3377

Answers (3)

vascowhite
vascowhite

Reputation: 18440

The easiest way to get seconds between two DateTime objects is to do a simple subtraction:-

$dteStart = new DateTime($statusTime);
$dteEnd = new DateTime($currentTime);
$seconds = $dteEnd->getTimestamp() - $dteStart->getTimestamp();

Upvotes: 0

Andreas
Andreas

Reputation: 23958

Strtotime will give you the time in seconds from 1 of january 1970.

So:

$statustimeUNIX = Strtotime(date("hh:mm:ss",$statusTime));
$currenttimeUNIX = Strtotime(date("hh:mm:ss", $currentTime));

$DiffInSeconds = $currenttimeUNIX - $statustimeUNIX; // or if it's supposed to be the other way around maybe?

There is no need for datetime here unless you need it for something else?

EDIT:

$statustimeUNIX = Strtotime(date("hh:mm:ss",$statusTime));
$currenttimeUNIX = Strtotime(date("hh:mm:ss", $currentTime));

$DiffInSeconds = $currenttimeUNIX - $statustimeUNIX;
If($DiffInSeconds > 300 || ($DiffInSeconds > -86100 && $DiffInSeconds < 0)){
   Echo "inactive";
}else{
   Echo "active";
}

Upvotes: 0

Unex
Unex

Reputation: 1757

you can use strtotime() function which returns a unix timestamp.

strtotime($dteDiff->format()); should do the trick

Upvotes: 2

Related Questions