PHP script to subtract or deduct time. Tutorial with code and example

March 23, 2008

Often we need to subtract years, months, days, hours, minutes and even seconds from current time or any other time. Previously I wrote a script and/or tutorial on how to add time. This script is nothing but a little modified version of the previous script to deduct or subtract time. I wrote this script since several people often come to search the time adding script. So, I wrote this script to check if this is helpful for any one.

Okay. Here is the PHP function to subtract or decuct time.

<?php

function subtractTime($hours=0, $minutes=0, $seconds=0, $months=0, $days=0, $years=0)

{

$totalHours = date(“H”) – $hours;

$totalMinutes = date(“i”) – $minutes;

$totalSeconds = date(“s”) – $seconds;

$totalMonths = date(“m”) – $months;

$totalDays = date(“d”) – $days;

$totalYears = date(“Y”) – $years;

$timeStamp = mktime($totalHours, $totalMinutes, $totalSeconds, $totalMonths, $totalDays, $totalYears);

$myTime = date(“Y-m-d H:i:s A”, $timeStamp);

return $myTime;

}

?>

Now we call the function to test the output.

<?php

// Let us first see the current time

echo ‘Current Time: ‘ . date(“Y-m-d H:i:s A”);

echo ‘<BR>';

// Now let us deduct 5 hours, 2 days and 1 year from now

echo ‘New Time: ‘ . subtractTime(5,0,0,0,2,1);

?>

And here is a sample output:

Current Time: 2008-03-23 21:40:28 PM
New Time: 2007-03-21 16:40:28 PM

Thus, you can subtract or deduct time (such as second, minute, hour, day, month, year) easily with a simple function.

About these ads

14 Responses to “PHP script to subtract or deduct time. Tutorial with code and example”

  1. Ritu Says:

    Thank You so much Tanzilo! Its great. But how will this code behave at midnight if i just want 5 min. to be subtracted every time my page refreshes ?

    I am working with MySql and PHP to get the data which is 5/10 minutes old and display corresponding values keeping the date as current.

    Really this was so helpful. Thanks a lot.

  2. Ritu Says:

    Also if you could help me with comparing the current date to the date stored in the database table.

    I am displaying the response time of my server in graph and for that I need updated data corresponding to current date and last 10 minutes of activity.

    So please please help me if you can.

    Thanks!

  3. tanzilo Says:

    Ritu,

    You are welcome.

    But let me have a look at your code.
    I will have a look and hopefully I can solve it.

    Do you want to refresh your page after every five minutes?

    Ok.
    Why don’t you use HTML code?
    If you use HTML “refresh” from META tag,
    you can refresh your code every 300 seconds.

    Please let me know if I did not understand you in correct way.


    Tanzilo

  4. Ritu Says:

    Hi Tanz!

    Yes I can refresh my page every 5 mins but then I want only the last 5 min. data from the database and not all of it. So my code is something like this, I am using your code and adding my modifications to it.

    <?php
    include ‘../library/config.php';
    include ‘../library/opendb.php';

    // Let us first see the current time
    echo ” Current Time: ” . date(“Y-m-d G:i:s “);
    echo “”;

    $newTime = subtractTime(0,5,0,0,0,0);

    // Now let us deduct 5 min from now
    echo “New Time: ” . $newTime ;
    echo “”;

    $q1 = “SELECT time, requests, total FROM webserver WHERE node = ‘a’ AND time >= ‘$newTime'”;
    $rs1 = mysql_query($q1) or die( ‘Query failed! ‘ . $q1 . ”. mysql_error());
    $rcount1 = mysql_num_rows($rs1);

    for($i=0; $i < $rcount1 ; $i++ )
    {
    list($time, $requests, $total) = mysql_fetch_array($rs1);
    echo(“$time, $requests, $total “);

    }

    include ‘../library/closedb.php';
    ?>

    So I want the query to work. Time is stored as ‘TIME’ format in database and accordingly I formated the date function to match that. I wonder how it will work at midnight.

    Thanks!

    Ritu

  5. Ritu Says:

    I added another comparison in the query and it works fine but still doubtful about the midnight.

    $q1 = “SELECT date, time, requests, total FROM webserver WHERE node = ‘a’ AND time >= ‘$newTime’ AND date=’$currentDate’ “;

    Thanks a lot! your code really helped me :)

  6. tanzilo Says:

    Hey Ritu,

    Thank for your posting.

    I am very busy right now with some scheduled tasks.

    I hope to solve your problem by tomorrow.
    Sorry for my delay.
    But I hope to come up tomorrow with the answer.

    Thanks. :)

  7. Frank Bishop Says:

    Thanks very much for this script, i needed it very much to complete the freelance job I just got at http://www.glolance.com. :)

  8. tanzilo Says:

    Hello Frank,

    I am glad to know that my code was helpful for you.

    Wishing you all the best.
    And hope that you will do great in your job.

  9. tanzilo Says:

    Hello Ritu,

    Ok.
    If you want to check a time during 12:00 at night or 00:00 whatever you say, that is OK.

    You can test it like this:
    First test in the localhost/in your PC.
    Set the time of your PC to something like:
    2008-04-30 23:59:55 or 30 April 2008 23 hours 59 minutes 55 seconds.

    Now run your code in every seconds and check the value when it is the perfect midnight time.

    I think the results will be identical in your server too.

    What do you think?

  10. Ritu Says:

    Ya time is working fine but the query I have to collect data from database isn’t as the date changes at midnight and my query isn’t correct as it checks for date=currentdate. Can u suggest something to do with my query so that it picks data post midnight also?

    For example I want the data at 00:10:00 for last 20 mins so how to work with date function to get data from 23:50:00 till 00:10:00 keeping in mind that date changes at midnight.

    $q1 = “SELECT date, time, requests, total FROM webserver WHERE node = ‘a’ AND time >= ‘$newTime’ AND date=’$currentDate’ “;

    Thank You so much in advance…

    Ritu

  11. tanzilo Says:

    Hey Ritu,

    There are built-in MONTH(), YEAR() functions in MySQL.
    If you pass your date/datetime as parameter in any of the functions, it will extract the desired value.

    Did you try something like this?
    $sql_query = “SELECT DISTINCT(order_id) FROM orders WHERE MONTH(receiving_date) = $month AND YEAR(receiving_date) = $year “;

    Let me know if it works for you.

  12. Ritu Says:

    No Tanzilo, it doesn’t work for me! it will be more complex than this. Selecting data at midnight when date changes. YEAR() AND MONTH() will not actually affect anything.

    Thanks,

    Ritu

  13. tanzilo Says:

    But my subtractTime function should work automatically during mid night.

    Did you check/test the function just on mid night?
    Are you sure that it does not work on mid night?

  14. tacuong Says:

    it’nt automatic change day or month or year.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: