Wie fügt man in PHP korrekt 30 Minuten zum H:i-Zeitformat hinzu?

Linda Hamilton
Freigeben: 2024-10-18 12:00:55
Original
571 Leute haben es durchsucht

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>
Nach dem Login kopieren
  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
Nach dem Login kopieren

Das obige ist der detaillierte Inhalt vonWie fügt man in PHP korrekt 30 Minuten zum H:i-Zeitformat hinzu?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:php
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Neueste Artikel des Autors
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!