1

Im trying to add seconds to a result from a variable

So what happens is:

for example:

$eta = "14:12:00";   // this is an example from another result    

then i have

$newseconds = "6" //where 6 is the seconds which randomly change

Now what i want to get working is that the newseconds whill be added to the eta

so that the end result will be 14:12:06

How can i do this?

I now have something like

echo date('H:i:s',strtotime('+12 seconds',strtotime($eta))).PHP_EOL

but the +12 seconds should then be coming from newseconds...

Thank you for the help

4
  • use timestamps ??.. Commented Dec 17, 2019 at 13:04
  • @Vidal timestamps are only machine-readable, often is more useful using human-readable date-time formats. Commented Dec 17, 2019 at 13:25
  • all solutions are using timestapms... strtotime returns a timestamp then they add the desired value and use date to format the timestamp to their desired format. ("H:i:s") Commented Dec 17, 2019 at 13:34
  • @Vidal yep, but the difference I'm talking about is the value that all of us can read in the code/Web: the human-readable format. Commented Dec 17, 2019 at 14:00

3 Answers 3

4

You can add seconds like this:

echo $newTime = date('H:i:s', strtotime("$eta + $newseconds seconds"));

output:

14:12:06

Try it here.

As you see, you can enclose the whole calculation between " ", so it's more readable.

Also, you need to call strtotime once, which makes the script faster.

You can learn more about strtotime in the official documentation.

Sign up to request clarification or add additional context in comments.

Comments

2

Just concat $newseconds to the added time string:

$eta = "14:12:00";
$newseconds = "6";
echo date('H:i:s',strtotime(+$newseconds.' seconds',strtotime($eta)));

Result 14:12:06 example

6 Comments

"+" should be in quotes, shouldn't it?
It doesn't have to be @droopsnoot sandbox.onlinephpfunctions.com/code/…
Ah, learn something new every day. So glad I phrased it that way.
Looks like you can remove the + as well(but will be less readable for humans).
Nice find @vivek_23!
|
0

Why not using PHP 's own DateTime class?

$seconds = 6;
$time = '14:12:00';

echo DateTime::createFromFormat('H:i:s', $time)
    ->modify('+' . $seconds . 'seconds')
    ->format('H:i:s');

Using the DateTime class enabled method chaining and you can use all methods this object includes. Read more in the documentation under PHP: DateTime - Manual.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.