Home  >  Article  >  Backend Development  >  How to Add or Subtract 30 Minutes to a Time String in PHP?

How to Add or Subtract 30 Minutes to a Time String in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-10-18 12:21:031121browse

How to Add or Subtract 30 Minutes to a Time String in PHP?

How to Add and Subtract 30 Minutes to a Time String in PHP

For clarity, you're aiming to manipulate a time value formatted as "H:i" by adding and subtracting 30 minutes. Let's delve into the process.

Defining the Function

<code class="php">$time = '10:00'; // Assuming 'H:i' format

// Calculate start and end times
$startTime = date("H:i", strtotime('-30 minutes', strtotime($time)));
$endTime = date("H:i", strtotime('+30 minutes', strtotime($time)));</code>

Explanation:

  1. Convert the given time string to a timestamp using strtotime. This interpretation makes it easier to manipulate.
  2. Use the strtotime function with an offset of -30 minutes to create a new timestamp representing 30 minutes before the original time. Then convert it back to a string in "H:i" format using date.
  3. Perform a similar process for the end time, but with an offset of 30 minutes.

Result:

Running this code with an input time of '10:00' will generate the following:

$startTime = '09:30'
$endTime = '10:30'

The above is the detailed content of How to Add or Subtract 30 Minutes to a Time String in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn