I have a form that receives a time value:
$selectedTime = $_REQUEST['time'];
The time is in this format - 9:15:00 - which is 9:15am. I then need to add 15 minutes to this and store that in a separate variable but I'm stumped.
I'm trying to use strtotime without success, e.g.:
$endTime = strtotime("+15 minutes",strtotime($selectedTime)));
but that won't parse.
For this, you can use the strtotime() method. $anyVariableName= strtotime('anyDateValue + X minute'); You can put the integer value in place of X.
To add minutes to a datetime you can use DATE_ADD() function from MySQL. In PHP, you can use strtotime(). select date_add(yourColumnName,interval 30 minute) from yourTableName; To use the above syntax, let us create a table.
php $time = "01:30:00"; list ($hr, $min, $sec) = explode(':',$time); $time = 0; $time = (((int)$hr) * 60 * 60) + (((int)$min) * 60) + ((int)$sec); echo $time; ?>
The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.
Your code doesn't work (parse) because you have an extra )
at the end that causes a Parse Error. Count, you have 2 (
and 3 )
. It would work fine if you fix that, but strtotime()
returns a timestamp, so to get a human readable time use date()
.
$selectedTime = "9:15:00"; $endTime = strtotime("+15 minutes", strtotime($selectedTime)); echo date('h:i:s', $endTime);
Get an editor that will syntax highlight and show unmatched parentheses, braces, etc.
To just do straight time without any TZ or DST and add 15 minutes (read zerkms comment):
$endTime = strtotime($selectedTime) + 900; //900 = 15 min X 60 sec
Still, the )
is the main issue here.
Though you can do this through PHP's time functions, let me introduce you to PHP's DateTime
class, which along with it's related classes, really should be in any PHP developer's toolkit.
// note this will set to today's current date since you are not specifying it in your passed parameter. This probably doesn't matter if you are just going to add time to it. $datetime = DateTime::createFromFormat('g:i:s', $selectedTime); $datetime->modify('+15 minutes'); echo $datetime->format('g:i:s');
Note that if what you are looking to do is basically provide a 12 or 24 hours clock functionality to which you can add/subtract time and don't actually care about the date, so you want to eliminate possible problems around daylights saving times changes an such I would recommend one of the following formats:
!g:i:s
12-hour format without leading zeroes on hour
!G:i:s
12-hour format with leading zeroes
Note the !
item in format. This would set date component to first day in Linux epoch (1-1-1970)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With