Home » Php » string – php – How To Convert 1 day To Seconds

string – php – How To Convert 1 day To Seconds

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am creating a form to set publish interval and want to sum all of the submitted values into seconds. The form consist of fields to determine seconds, minutes, hours, day and so on.

I am collecting the submitted values to string by giving date attributes, like second, minute etc.

For example:

$second second

$minute minute

$hour hour

So if user input 1 in input field to determine the interval in day and 30 in minute, then my code will convert it to string 1 day and 30 minute.

My questions:

1- How can I convert 1 day and 30 minute string into seconds so they can be summed up into correct seconds.

I tried to use strtotime() but it returns a very large number of seconds and date() but it return too small number.

2- Is there a simple function like strtotime() and date() that can do string to second conversion correctly?

How to&Answers:

You can use strtotime() with a second parameter, like following:

strtotime('1 day 30 second', 0);

This will give you 86430, which is the number of seconds in 1 day and 30 seconds.

(If the second parameter is omitted, the current timestamp (i.e. time()) is used to add what is specified in the string, which leads to the big number.)

Answer:

Try the following code:

$day = 1;
$hour = 1;
$minute = 1;
$second = 0;
$second += (($day * 24 + $hour) * 60 + $minute) * 60;