【问题标题】:Get date of next Sunday after a certain time?在特定时间后获取下周日的日期?
【发布时间】:2016-02-09 10:18:57
【问题描述】:

我需要在某个截止点之后返回下周日的日期。例如 - 我正在运营一个竞赛网站,截止日期是每周周日晚上 10 点,因此如果用户在周日晚上 10 点之后查看该网站,则需要显示下周日期。

目前我正在使用这个:

date('F jS', strtotime('this Sunday', strtotime(date('F jS', time()))));

这很好,但只能在午夜之后工作,所以只会在周一 00:00 显示下周日的日期,而我在周日 22:00 需要它。

非常感谢任何帮助!

【问题讨论】:

  • 您不能使用满足您要求的时区来解决它。希腊是 GMT+2,

标签: php date


【解决方案1】:

像这样简单的东西就足够了吗?

$competitionDeadline = new DateTime('this sunday 10PM');

$date = new DateTime();

if ($date->format('l') === 'Sunday' && $date->format('H') >= '22') {
    // It is past 10 PM on Sunday, 
    // Override next competition dates here... i.e.

    $competitionDeadline = new DateTime('next sunday 10PM');
}

// Wherever you are presenting the competition deadline...
$competitionDeadline->format('Y-m-d H:i:s');

【讨论】:

  • 我不会使用硬编码的日期,而是将 $competitionDeadline 构造为带有“下周日晚上 10 点”的 DateTime 对象。除此之外,这种方法对我来说看起来不错。
  • @Oldskool 你完全正确,我会用你的建议更新 OP,^_^
  • 很好的编辑。如果今天不是星期天,或者如果它是星期天并且小时少于 22,会发生什么?不过,可读性比其他答案要好。
  • 因为我们今天在这里都认识到我们的错误,这是正确的。此代码在 22:00 之后除星期日以外的任何一天生成以下错误 Notice: Undefined variable: competitionDeadline on line 11
  • 在时间检查中添加了另一个次要(但重要)编辑,以确保比赛日期从 22:00 开始(而不是 23:00)“快进”。
【解决方案2】:

你需要先检查一下今天是不是星期天,时间是否小于晚上 10 点:

$next = 'next'; //default to 'next', only change if below matches:
if (date('N') == '7' && date('h') < 22) $next = 'this';

现在在您的 strtotime 中使用该变量:

date('F jS', strtotime("$next Sunday"));

3v4l proof of concept

【讨论】:

  • 当然提问者早已不复存在,并且不会接受我们现在的任何原始答案。 Hase la vie 仍然保持清洁,这是最重要的事情
  • @RiggsFolly 至少,如果他们真的回来,他们有几个不错的选择 =)
【解决方案3】:

试试这个,

echo date('F jS', strtotime('this Sunday', time() + (2*60)));

【讨论】:

  • 我更喜欢这个答案,因为它很简单!当您将星期日视为一周中的最后一天时,这非常有意义,因此添加两个小时会使您进入下一周(仅当它是星期日 >= 晚上 10 点时)
【解决方案4】:

由于您的代码返回下周日 @ 00:00:00 的时间戳,只需在检查您是否在周日之前以及截止时间之前或之后添加 22 小时即可。

// work out if we what this sunday or next sunday
// based on whether we are before or after the cutoff of 22:00
$when = (date('N') == '7' && date('h') > 22) ? 'this' : 'next';

$comp_finish = strtotime("$when Sunday") + (60*60*22);
echo date('d/m/Y H:i:s', $comp_finish);

给予

14/02/2016 22:00:00

您也不需要使用第二个strtotime,因为它只会生成与第一个strtotime 相同的now

【讨论】:

  • @BobNocraz 感谢您的 DV,我赞成您的问题,因为它似乎确实考虑到了我设法错过的内容,即如果已经是星期天,您所在的地方
  • 已删除我以前的 cmets。我同意它现在是一个可行的答案。您可以通过在函数中包含时间来改进您的strtotime 行:strtotime("$when Sunday 22:00:00"); 但这只是我很挑剔=/
  • @BobNocraz 选择,你在我错过了主要要求的答案上拉我是正确的。
猜你喜欢
  • 2011-09-14
  • 2021-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多