Hi, I have to try and work out if a unix timestamp is between 21 days and 49 days from the current date. Can anyone help me to work this out? Thanks!
+5
A:
Welcome to SO!
This should do it:
if (($timestamp > time() + 1814400) && ($timestamp < time() + 4233600)) {
// date is between 21 and 49 days in the FUTURE
}
This can be simplified, but I thought you wanted to see a more verbose example :)
I get 1814400 from 21*24*60*60 and 4233600 from 41*24*60*60.
Edit: I assumed future dates. Also note time() returns seconds (as opposed to milliseconds) since the Epoch in PHP.
This is how you do it in the past (since you edited your question):
if (($timestamp > time() - 4233600) && ($timestamp < time() - 1814400)) {
// date is between 21 and 49 days in the PAST
}
David Titarenco
2010-06-27 18:29:23
Thanks David, perfect! It's between 21 and 49 days in the past, so i'll just modify your snippet
pauld78
2010-06-27 18:34:28
Yep, I fixed it as well :p
David Titarenco
2010-06-27 18:35:50
Be aware that some some days are shorter/longer than 24 hours due to daylight savings etc which makes the calculations shaky. I generally avoid doing calculations on raw timestamps like that and instead use built-in functions for date manipulations.
Martin Wickman
2010-06-27 21:27:24
+3
A:
The PHP5 DateTime class is very suited to these sort of tasks.
$current = new DateTime();
$comparator = new DateTime($unixTimestamp);
$boundary1 = new DateTime();
$boundary2 = new DateTime();
$boundary1->modify('-49 day'); // 49 days in the past
$boundary2->modify('-21 day'); // 21 days in the past
if ($comparator > $boundary1 && $comparator < $boundary2) {
// given timestamp is between 49 and 21 days from now
}
Jon Cram
2010-06-27 18:34:28
+3
A:
strtotime is very useful in these situations, since you can almost speak natural english to it.
$ts; // timestamp to check
$d21 = strtotime('-21 days');
$d49 = strtotime('-49 days');
if ($d21 > $ts && $ts > $d49) {
echo "Your timestamp ", $ts, " is between 21 and 49 days from now.";
}
nikc
2010-06-27 18:35:02
While in this example it may be trivial, the time() function in PHP 5.2.13 source is one line of C code while the strtotime() function is about 55 lines and calls a LOT of externals. If this was used in a loop especially, time() would be the way to go.
TomWilsonFL
2010-06-27 19:23:58
That's true. But if you only need to set a timestamp once, it's not too expensive when you consider the increased readability.
nikc
2010-06-27 19:37:40
+1 For using built-in functions which accounts for locale related date issues.
Martin Wickman
2010-06-27 21:28:55