Hello guys, today I'm doing to show you how to compare DateTime (Now()) in a simple SQL query.
You should know, the NOW() DateTime format goes like:
Alright, now lets get down to business!
1) Getting your dates to compare.
If you don't have any dates to compare, well, let's get a couple!
Run this query:
You should see the current date and the time you ran the query. Mine is:
I mentioned we should get a couple, but we should add a custom one ourselves to compare with.
2) Comparing your dates
Comparing the dates you have is rather simple. We should compare how many days apart it would be from now to sometime next month.
Make sure you have the date we received in 1) of this tutorial.
Running this query, I will have a date that is changed to next month, like so:
Also note: If date1's date is lower than date2, it will return in the negative, which implies that the date was -X days ago.
Run this query:
SELECT DATEDIFF('2013-06-28 07:45:29','2013-05-24 07:00:29')
The result should be:
2.1) Returning 1 or 0 if wanting to compare dates <= or >=
I just used this method yesterday and it worked well! What you can do is compare a date and if that date is > or < X days, it would return a 1 or 0.
For example, if I did:
SELECT DATEDIFF('2013-06-28 07:45:29','2013-05-24 07:00:29') = 35
If above is comparing those two dates, but I'm also checking to see if it equals 35. My result should return a 1, but if I wrote = 34, it would return 0 because it does not equal 34.
You can also do greater than and less than or greater than equal to & less than equal to.
SELECT DATEDIFF('2013-06-28 07:45:29','2013-05-24 07:00:29') > 35
The above would return 0, because it is 35 even.
But if I did:
SELECT DATEDIFF('2013-06-28 07:45:29','2013-05-24 07:00:29') >= 35
It would return 1.
I hope you enjoyed this tutorial! Not much but it gets the job done.