php添加小时日期输出错误的结果

时间:2010-06-12 13:11:40

标签: php datetime

基本上我想要做的是发送电子邮件,以便在3小时后跟进订单。

我尝试做的是获取当前日期(最多几小时),然后与orderdate + 3小时进行比较,看看它是否匹配。

示例orderdate:2010-06-12 18,添加3小时后应该成为2010-06-12 21

然而,在添加小时后,最终结果有时会变得更大,有时会变得更小......出错了。

$now= date('Y-m-d H');
echo $now . "<br>";


...
...

while ($data = mysql_fetch_array ($result))
{
 $orderid = $data['orderid'];
 $orddate = $data['orddate'];
 $corddate= date('Y-m-d H:i:s', $orddate);


 $year = substr ($corddate, 0, 4);
 $month = substr ($corddate, 5, 2);
 $day = substr ($corddate, 8, 2);
 $hour = substr ($corddate, 11, 2);
 $actualorderdate= $year . "-" . $month . "-" . $day . " " . $hour;


 $new_time = mktime ($hour+3, 0, 0, $month, $day, $year);
 $year = date ('Y', $new_time);
 $month = date ('m', $new_time);
 $day=  date ('d', $new_time);
 $hour=  date ('h', $new_time);
 $xhourslater= $year . "-" . $month . "-" . $day . " " . $hour;


 echo "actualorderdate: ". $actualorderdate. " xhourslater: " . $xhourslater. "<br>";

 if($now==$xhourslater)
 {
  echo "now is 3 hours later" . "<br>";
  //send email follow up, then update status as sent, in order not to resend anytime in the 3rd hour.

 }


}

2 个答案:

答案 0 :(得分:1)

对我来说,就好像你正在进行大量过多的解析一样。

$orddate = $data['orddate'];
$actualOrderDate = date('Y-m-d H:i:s', $orddate);
$timeToSendEmail = date('Y-m-d H:i:s', strtotime('+3 hours', $orddate)); //Assuming $orddate is a timestamp int. If not, you'll have to do some calculations or something there, possibly using date() again.

基本上,你只想让订单时间+3小时,所以使用php的strtotime(http://php.net/manual/en/function.strtotime.php)函数。非常有帮助。

如果这不是您想要的,请发布一些测试数据,以便更容易找出可能会变得有趣的内容。

答案 1 :(得分:0)

我认为

更简单
$date_now  = date( "Y-m-d g:i a" ); // get the date
$time_now  = time( $date_now ); // convert it to time
$time_next = $time_now + 3 * 60 * 60; // add 3 hours (3 x 60mins x 60sec)
$date_next = date( "Y-m-d H", $time_next); // convert it back to date