The UNIX timestamp is the number of seconds elapsed since January 1, 1970 at 00:00:00. I use the timestamp mostly, it's better for doing arithmetical operations as it is just a number. For me it's easier to add or subtract thousands of seconds than doing the same with a date string. I'm going to use both timestamps and date strings although prefer the first. Printing the current timestamp is as simple as . This function alone doesn't do much, the result is a number with more than nine figures, almost unreadable for the average user including me. I'm not going to enter into details about this topic as it has been covered in previous articles. Let's go to the examples… Calculating days, hours and seconds PHP lacks date operation functions, but it provides the tools to do what we want to do. Say we want to know how many days, hours and seconds exist between two given dates, following is the function: // The parameters of this function are the dates to be compared. // The first should be prior to the second. The dates are in // the form of: 1978-04-26 02:00:00. // They also can come from a web form using the global $_POST['start'] // and $_POST['end'] variables. function date_diff($str_start, $str_end) { $str_start = strtotime($str_start); // The start date becomes a timestamp $str_end = strtotime($str_end); // The end date becomes a timestamp $nseconds = $str_end - $str_start; // Number of seconds between the two dates $ndays = round($nseconds / 86400); // One day has 86400 seconds $nseconds = $nseconds % 86400; // The remainder from the operation $nhours = round($nseconds / 3600); // One hour has 3600 seconds $nseconds = $nseconds % 3600; $nminutes = round($nseconds / 60); // One minute has 60 seconds, duh! $nseconds = $nseconds % 60; echo $ndays." days, ".$nhours." hours, ".$nminutes." minutes, ".$nseconds." echo "seconds "; } // Test the function with several values date_diff("1978-04-26", "2003-01-01"); date_diff("1984-10-24 15:32:25", "2003-01-01"); date_diff("2001-10-28 17:32:25", "2003-01-01 12:00:18"); ?> We could implement more options such as date validation etc., but I will add that in future articles. This function does not need a lot of explanation, just multiplication and division. Now, let's seeanother example.
blog comments powered by Disqus |
|
|
|
|
|
|
|