使用PHP在DateTime中减去小时和减去小时

时间:2012-01-24 10:08:43

标签: php datetime

<?php

$one = new DateTime('2012-01-24 13:00');
$two = new DateTime('2012-01-24 06:00');
$three = new DateTime('2012-01-24 08:42');
$four = new DateTime('2012-01-24 12:00');
$five = new DateTime('2012-01-24 06:33');

$array = array($one, $two, $three, $four, $five);

foreach($array as $a){
   $a->modify("-7 hours");

   echo $a->format('Y-m-d H:i') . "\n";
}

LIVE: http://codepad.org/JgoX3y7O

我想在 23:00-05:00 之间显示没有小时的日期。如果日期在这个范围内,那么应该在没有这些时间的情况下做负。 我的例子显示:

2012-01-24 06:00
2012-01-23 23:00
2012-01-24 01:42
2012-01-24 05:00
2012-01-23 23:33

但应该是:

2012-01-24 06:00
2012-01-23 17:00 
2012-01-24 19:42
2012-01-24 05:00
2012-01-23 17:33

$ one $ 4 都可以,因为12:00-7:00和13:00-7:00不在23:00-范围内05:00

我该怎么做?

2 个答案:

答案 0 :(得分:3)

根据你的评论,我只能猜测你试图“跳过”一段时间。然后,您应该在这段时间内添加“惩罚”,例如:

foreach($array as $a){
   $a->modify("-7 hours");

   // Is the time within the 'skip period'?
   if($a->format('H') >= 23 || $a->format('H') < 5) {
       // The calculation got a time between 23:00 - 05:00, add time penalty!
       $a->modify("-6 hours");
   }

   echo $a->format('Y-m-d H:i') . "\n";
}

答案 1 :(得分:1)

根据我的理解你的问题,你想从日期/时间减去7小时,除非结果在23:00-05:00的间隔内,那么应该减去另外6个小时。我建议做这样的事情:

<?php
$array = array(
  new DateTime('2012-01-24 13:00'),
  new DateTime('2012-01-24 06:00'),
  new DateTime('2012-01-24 05:59'),
  new DateTime('2012-01-24 08:42'),
  new DateTime('2012-01-24 12:00'),
  new DateTime('2012-01-24 11:59'),
  new DateTime('2012-01-24 06:33')
);

foreach($array as $a) {
  $a->modify("-7 hours");
  if(($a->format('H') + 1) < 6) {
    $a->modify("-6 hours");
  }
  echo $a->format('Y-m-d H:i') . "\n";
}
?>

这应输出

2012-01-24 06:00
2012-01-23 17:00
2012-01-23 22:59
2012-01-23 19:42
2012-01-24 05:00
2012-01-24 22:59
2012-01-23 17:33

修改 你也可以在循环中做一个单行程

foreach($array as $a) {
  echo $a->modify((($a->format('H') + 1) < 6) ? '-13 hours' : '-7 hours')->format('Y-m-d H:i') . "\n";
}