Theory: How to compare dates in PHP.
Posted: Wed Nov 06, 2002 11:03 am
I've noticed a lot of people(in this forum as well as other pleaces)asking about dates/times and how to compare them to current dates/times. I'm here to post the theory behind it, but not the code.
Need: To compare a stored date agaisnt the current date.
First I would suggest saving the dates in a certain format so that they can be delimited easliy later on. For example 10!29!1976. When you need to compare, you can use the explode function to break that down into three variables, 10, 29, 1976. Then it is just a simple matter of comparing... if $today.month >= $saved.month { blah blah blah...
If the date is not saved in a format that is easliy delimited it would just take more code to break it down into variables. A lot of 'if then else' statements would do the trick.
A note about UNIX time.
The time() function returns the number of seconds since January 1 1970 00:00:00 GMT. If you store that number with, say, a news entry, then it is infinatly easier to compare later on when you need to run clean-up scripts. Finding the latest 5 postings would involve a lot less code.
So that's pretty much how it is done. If you are starting a new program, an you know you will need to reference stuff by date try to include the time() function to the list of variables assigned to each group. Some situations, though, might be easier to use the explode method.
After all, in programming, anything is possible, all you need to do is write one more line of code.
-seg
p.s. If someone wants to translate some of all of this into code that would be nice.
Need: To compare a stored date agaisnt the current date.
First I would suggest saving the dates in a certain format so that they can be delimited easliy later on. For example 10!29!1976. When you need to compare, you can use the explode function to break that down into three variables, 10, 29, 1976. Then it is just a simple matter of comparing... if $today.month >= $saved.month { blah blah blah...
If the date is not saved in a format that is easliy delimited it would just take more code to break it down into variables. A lot of 'if then else' statements would do the trick.
A note about UNIX time.
The time() function returns the number of seconds since January 1 1970 00:00:00 GMT. If you store that number with, say, a news entry, then it is infinatly easier to compare later on when you need to run clean-up scripts. Finding the latest 5 postings would involve a lot less code.
So that's pretty much how it is done. If you are starting a new program, an you know you will need to reference stuff by date try to include the time() function to the list of variables assigned to each group. Some situations, though, might be easier to use the explode method.
After all, in programming, anything is possible, all you need to do is write one more line of code.
-seg
p.s. If someone wants to translate some of all of this into code that would be nice.