我正在编写一个函数来计算时间是否在工作日的上午 9 点到下午 5 点之间。然后,它会根据今天的营业时间是否已经结束或(如果在午夜之后)即将开始,告诉您下一个工作日的开始时间(如果当前是非营业时间)。
到目前为止一切都很顺利,并且创建了我可以使用的最易读的代码strtotime()
——但是你如何测试strtotime()
呢?
有没有办法临时更改系统时间以进行测试?
只需使用strtotime()
的可选第二个参数,给它一个特定的时间戳来使用。如果您不提供第二个参数,它将使用当前时间。
strtotime 接受第二个参数,将时间设置为您想要的任何时间,而不是当前时间
int strtotime ( 字符串 $time [, int $now ] )
$time 是模仿的格式
$now 是生成日期的时间戳
如果现在提供它会覆盖当前时间。
例如在 3 月 30 日星期一下午 6 点进行测试,无论程序何时运行
$format = '2009-03-30 18:00'
$timestamp = mktime(18,0,0,3,30,2009);
strtotime($format,$timestamp);
看看这个页面,这就是你所需要的。:)
要测试 strtotime,您可以使用http://www.teststrtotime.com(按 Enter 提交表单,该按钮现在似乎坏了)。
为什么不只是一个具有 strtotime() 输入值数组的单元测试?
...
test( strtotime("now") );
test( strtotime("10 September 2000") );
test( strtotime("+1 day") );
test( strtotime("+1 week") );
test( strtotime("+1 week 2 days 4 hours 2 seconds") );
test( strtotime("next Thursday") );
test( strtotime("last Monday") );
你甚至不需要为 strtotime() 使用第二个参数;
// $now = time( ); // use this once testing is finished
$now = strtotime( '03/15/2009 14:53:09' ); // comment this line once testing is complete
testTime( $now );