Current Location: Home> Latest Articles> Practical PHP Time Handling: How to Accurately Remove Seconds

Practical PHP Time Handling: How to Accurately Remove Seconds

M66 2025-08-08

PHP Time Handling Techniques: Detailed Methods to Remove Seconds

Time handling is a very common task in programming, and how to manage time in PHP is a key focus for developers. This article will focus on how to remove seconds from time in PHP, providing concrete code examples to help you better understand and apply these techniques.

In many scenarios, it is necessary to handle time accurate to the minute while ignoring the seconds, which simplifies time display and calculations, improving code readability and accuracy.

Removing Seconds Using strtotime() and date() Functions

$timestamp = strtotime("now");
$timestamp = $timestamp - ($timestamp % 60);
$time_without_seconds = date("Y-m-d H:i", $timestamp);
echo $time_without_seconds;

Code Explanation:

  • Use strtotime("now") to get the current timestamp;
  • Use modulo operation on the timestamp to set the seconds part to zero;
  • Format the timestamp using date("Y-m-d H:i", $timestamp) to exclude seconds;
  • Output the time string without seconds.

Removing Seconds Using the DateTime Class

$date = new DateTime();
$date->setTime($date->format('H'), $date->format('i'), 0);
$time_without_seconds = $date->format('Y-m-d H:i');
echo $time_without_seconds;

Code Explanation:

  • Create a new DateTime object representing the current time;
  • Use the setTime() method to set seconds to zero;
  • Format the time with format('Y-m-d H:i') to remove seconds;
  • Output the time string without seconds.

Summary

Both methods above effectively remove seconds from PHP time. Choose the appropriate approach based on your project needs to improve maintainability and readability. Mastering these time handling techniques will make your time data processing more accurate and efficient.