2010-06-27 213 views
1

如果unix时间戳是从当前日期起21天到49天之间,我必须尝试一下。任何人都可以帮我解决这个问题吗?谢谢!unix时间戳之间的时差

+0

从当前日期的哪个方向开始21到49天?过去还是未来? – 2010-06-27 18:27:52

+0

对不起,忘了提及那个关键的细节!在过去 – pauld78 2010-06-27 18:32:11

回答

5

欢迎来到SO
这应做到:

if (($timestamp > time() + 1814400) && ($timestamp < time() + 4233600)) { 
// date is between 21 and 49 days in the FUTURE 
} 

这可以简化,但我想你想看到一个更详细的例子:)

我从21*24*60*601814400423360041*24*60*60

编辑:我假设未来日期。另请注意time()返回(而不是毫秒)自PHP中的Epoch以来。

这是你如何做到这一点的过去(因为你修改你的问题):

if (($timestamp > time() - 4233600) && ($timestamp < time() - 1814400)) { 
// date is between 21 and 49 days in the PAST 
} 
+0

谢谢大卫,完美!这是过去21至49天,所以我只是修改你的片段 – pauld78 2010-06-27 18:34:28

+0

是的,我也修正了它:p – 2010-06-27 18:35:50

+0

请注意,由于夏令时等原因,有些日子比24小时更短/更长,计算不稳定。我通常避免对这种原始时间戳进行计算,而是使用内置函数进行日期操作。 – 2010-06-27 21:27:24

3

的PHP5 DateTime类非常适合这些类型的任务。

$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 
} 
+0

对象矫枉过正> _ < – 2010-06-27 18:41:03

3

strtotime在这些情况下非常有用,因为您几乎可以说出自然的英语。

$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."; 
} 
+1

尽管在这个例子中它可能是微不足道的,PHP 5.2.13源代码中的time()函数是一行C代码,而strtotime()函数大约是55行,并且调用了很多外部代码。如果特别在循环中使用它,则time()将是要走的路。 – TomWilsonFL 2010-06-27 19:23:58

+0

的确如此。但是,如果您只需要设置一次时间戳,那么考虑提高可读性时,它不会太昂贵。 – 2010-06-27 19:37:40

+0

+1使用内置函数来说明与语言环境相关的日期问题。 – 2010-06-27 21:28:55