1. Computing

Discuss in my forum

The Mathematics of Time in PHP

How to add and subtract time in PHP

By , About.com Guide

In everyday life when we deal with time, we speak in seconds, minutes, hours, days, weeks, months, years, decades, centuries, etc.... you get the idea. When PHP deals with time it uses only one measurement, seconds. More specifically it measures time in seconds since January 1, 1970. Once we know how time works in PHP, it becomes easier to add, subtract, and calculate time. Below is a quick guide:

Time in Seconds
1 Minute: 60 seconds
1 Hour: 3,600 seconds
1 Day: 86,400 seconds
1 Week: 604,800 seconds
4 Weeks: 2,419,200 seconds
1 Year: 31,536,000 seconds
1 Decade: 315,360,000 seconds

Now let's put this into practice. Let's say for example you wanted to set a cookie in a user's browser to expire in one year. The way we would calculate this is by adding one year, or 31,536,000 seconds to the current date before setting the cookie:

 $Year = 31536000 + time() ; 
Perhaps you want to find out what calendar day occurs in a set period of time. This is what is done in pregnancy calendars. In this example we will find the calendar date that occurs in exactly 2 weeks (1209600 seconds) time.
 $twoweeks = 1209600 + time() ;
 echo date("M-d-Y", $twoweeks) ; 
 
Related Video
Basic PHP Syntax
Using PHP With HTML
  1. About.com
  2. Computing
  3. PHP / MySQL
  4. Advanced PHP
  5. Adding Time PHP - PHP Time Math

©2013 About.com. All rights reserved.