32 hours ago excluding weekends with php

烈酒焚心 提交于 2019-12-22 08:45:04

问题


So I have a script that does multiple checks for 32, 48 and 72 hours ago. Basically I check my database for entries that are at least x hours old.

Now this works fine like this:

$date = date('Y-m-d H:i:s',strtotime('-32 hours')); 
$q    = "SELECT * FROM `table` WHERE `date` <= '".$date."'";

Now I want this to exclude weekends. I know you can use weekdays within strtotime to get this effect however this doesn't work for hours.

For 48 hours it's easy because I can simply do the following:

echo date('Y-m-d H:i:s',
          strtotime(date("Y-m-d H:i:s").
          " -2 weekdays ".
          date('H:i:s')));

For 72 hours it's also easy because it's 3 days. However 32 hours poses a problem because it's ±1.3 days.

In conclusion, how do I get the datetime of 32 hours ago excluding weekends.


回答1:


Use strtotime as you had initially:

$time = strtotime('-32 hours');

Then do the weekend/weekday calculation manually.

// If the day is Sunday or Saturday subtract a full day.
while (date('w', $time) % 6 == 0) {
    $time = strtotime('-1 day', $time);
}
$date = date('Y-m-d H:i:s', $time);



回答2:


I am not sure if this is correct or the best way to do it but something like:

function getDateBackExcludingWeekend( $hours ) {
  $now = time();
  $secondsBack = $hours * 3600;

  $actual = $now - $secondsBack;
  $monday = strtotime("last monday");

  if( $actual < $monday ) {
    $diff = ($secondsBack - ($now - $monday));
    $backthen = ($monday - 172800 /* two days */) - $diff;

    return date("Y-m-d H:i:s", $backthen);
  }

  return date("Y-m-d H:i:s", $actual);
}



回答3:


Why not just remove two days and add 16 hours semi-manually to make up for it?

$DateTMP = date('Y-m-d h:i:s',(strtotime(date(Y-m-d)." -2 weekdays") + (60 * 60 * 16)));


来源:https://stackoverflow.com/questions/8136468/32-hours-ago-excluding-weekends-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!