How to Subtract Time from Current DateTime in PHP

Subtract time (hours, minutes, and seconds) from date can be easily done using the date() and strtotime() function in PHP. The date() function formats a local date and time, and returns a formatted string. On the other hand, the strtotime() function converts string formatted DateTime into Unix timestamp. You can use these two functions together to subtract time form the current date using PHP.

The following example code helps you to subtract time from current DateTime or a specific date-time.

Subtract Hours from Datetime
Use the following code snippet to subtract 2 hours from current date and time using PHP.

// Current date and time
$datetime date("Y-m-d H:i:s");

// Convert datetime to Unix timestamp
$timestamp strtotime($datetime);

// Subtract time from datetime
$time $timestamp - (60 60);

// Date and time after subtraction
$datetime date("Y-m-d H:i:s"$time);

Subtract Minutes from Datetime
Use the following code snippet to subtract 5 minutes from current date and time using PHP.

// Current date and time
$datetime date("Y-m-d H:i:s");

// Convert datetime to Unix timestamp
$timestamp strtotime($datetime);

// Subtract time from datetime
$time $timestamp - (60);

// Date and time after subtraction
$datetime date("Y-m-d H:i:s"$time);

Subtract Seconds from Datetime
Use the following code snippet to subtract 30 seconds from current date and time using PHP.

<?php
// Current date and time
$datetime date("Y-m-d H:i:s");

// Convert datetime to Unix timestamp
$timestamp strtotime($datetime);

// Subtract time from datetime
$time $timestamp 30;

// Date and time after subtraction
$datetime date("Y-m-d H:i:s"$time);

1 Comment

  1. Harshal Jani Said...

Leave a reply

keyboard_double_arrow_up