php - 匹配日期中的星期几()/时间()

时间:2011-04-23 08:46:43

标签: php events datetime date time

我正在尝试根据定期方法重新安排重复活动:每日,每周或每月。

假设我有这些数据:

  $now = time();
  $start_date = '01/01/2011 14:00';
  $end_date = '01/01/2011 14:20';
  $start_time = date('H:i', $start_date);
  $end_time = date('H:i', $end_date);
  $period = $end_date - $start_date; // in this case, 20 minutes

每天重新安排的活动将是:

  $new_time_start = strtotime(date("m/d/Y {$start_time}", $now));
  $new_time_end = $new_time_start + $period;

每月:

  $start_day = date('d', $start_date);
  $new_time_start = strtotime(date("m/{$start_day}/Y {$start_time}", $now));
  $new_time_end = $new_time_start + $period;

它似乎有效,但我不知道如何为每周事件做同样的事情:(

例如'01 / 01/2011'是星期六,所以我想重新安排活动每周六(根据PHP的第6天)运行。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

我不太清楚我理解你的问题,但你不能这样做吗?

$time       = '2011-01-31';
$weekLater  = date('Y-m-d', strtotime('+7 days ' . $time));
echo $time . ' -> ' . $weekLater;  

Output : 2011-01-31 -> 2011-02-07

无论你给它什么日期,它都会在未来7天给你一个日期。这是你需要的吗?

答案 1 :(得分:1)

试一试......

$today = date('w');
$day = date('w', $start_date);
$diff = abs(7 - ($today - $day));
$new_time_start = strtotime('+'.$diff.'days', strtotime(date("m/d/Y {$start_time}")));
$new_time_end = $new_time_start + ($end_date - $start_date);

好像你在$ start_date和$ end_date值周围缺少一些strtotime()包装器。我假设你将开始和结束日期变量存储为unix时间戳,所以我没有将它们包含在我的代码中。

另外,作为旁注,您不必在date()中输入time()作为第二个参数。如果缺少时间值,它将使用当前时间。因此,您可以删除所有$ now实例,它仍然有效。

相关问题