How to Correctly Add 30 Minutes to H:i Time Format in PHP?

Linda Hamilton
Release: 2024-10-18 12:00:55
Original
570 people have browsed it

How to Correctly Add 30 Minutes to H:i Time Format in PHP?

Troubleshooting Addition of 30 Minutes to H:i Time Format in PHP

The issue of adding 30 minutes to a time value formatted as H:i in PHP can be resolved by converting the time to a Unix timestamp before performing the addition. This ensures that the time calculation is done correctly.

As mentioned in the question, the original attempt used the strtotime function with the wrong argument. Here's the corrected approach:

<code class="php">$time = strtotime('10:00');
$startTime = date("H:i", strtotime('-30 minutes', $time));
$endTime = date("H:i", strtotime('+30 minutes', $time));</code>
Copy after login
  1. Convert the original time ($time) to a Unix timestamp using strtotime('10:00').
  2. Add 30 minutes to the timestamp using strtotime('-30 minutes', $time) to get the start time. Format it as H:i using date("H:i", strtotime(...)).
  3. Add 30 minutes to the timestamp using strtotime(' 30 minutes', $time) to get the end time. Format it as H:i using date("H:i", strtotime(...)).

By converting to a timestamp first, the addition of minutes can be performed correctly. This will result in the following output for an input of 10:00:

$startTime = 09:30
$endTime = 11:00
Copy after login

The above is the detailed content of How to Correctly Add 30 Minutes to H:i Time Format in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!