【问题标题】:PHP timestamp - first day of the weekPHP时间戳 - 一周的第一天
【发布时间】:2012-03-23 17:43:34
【问题描述】:

需要找到第一天第一分钟时间戳 >本周

最好的方法是什么?

<?php

$ts = mktime(); // this is current timestamp

?>

【问题讨论】:

标签: php datetime date time


【解决方案1】:

如果星期一是你的第一天:

$ts = mktime(0, 0, 0, date("n"), date("j") - date("N") + 1);

【讨论】:

  • 如果你想要星期天,就去掉 1:$ts = mktime(0, 0, 0, date("n"), date("j") - date("N"));
  • 谢谢,但如果星期一是上个月或上一年,这可能不起作用。
  • @acoder 好点!但是...我刚刚对其进行了测试,如果当前日期是例如 3 月 3 日,PHP 似乎可以很好地处理由date("j") - date("N") + 1 产生的负数。
  • @Mathieu 这是一个很好且有价值的通知,真的!该解决方案可以在 PHP5 中使用,因为根据 php 文档在 PHP 5.1.0 中添加了 date("N")。
  • ... 如果我们将 date("N") 更改为 date("w") 那么我想它也应该在 PHP4 中工作。
【解决方案2】:

如果您认为星期一是本周的第一天...

$ts = strtotime('Last Monday', time());

如果您认为星期日是本周的第一天...

$ts = strtotime('Last Sunday', time());

【讨论】:

  • 当今天是一周的第一天时,这似乎不起作用。例如,如果我们是星期一,strtotime('Last Monday') 将返回一周前的星期一,而不是本周的开始(今天午夜)
【解决方案3】:

如果您要查找的是星期一:

$monday = new DateTime('this monday');
echo $monday->format('Y/m/d');

如果是星期天:

new DateTime('this sunday'); // or 'last sunday'

有关这些相对格式的更多信息,请查看此处“PHP: Relative Formats

【讨论】:

  • OP 需要时间戳,而不是 DateTime
【解决方案4】:

首先,PHP 中的日期/时间函数真的很慢。所以我尽量给他们打电话。您可以使用getdate() 函数完成此操作。

这是一个灵活的解决方案:

/**
 * Gets the timestamp of the beginning of the week.
 *
 * @param integer $time           A UNIX timestamp within the week in question;
 *                                defaults to now.
 * @param integer $firstDayOfWeek The day that you consider to be the first day
 *                                of the week, 0 (for Sunday) through 6 (for
 *                                Saturday); default: 0.
 *
 * @return integer A UNIX timestamp representing the beginning of the week.
 */
function beginningOfWeek($time=null, $firstDayOfWeek=0)
{
    if ($time === null) {
        $date = getdate();
    } else {
        $date = getdate($time);
    }

    return $date[0]
        - ($date['wday'] * 86400)
        + ($firstDayOfWeek * 86400)
        - ($date['hours'] * 3600)
        - ($date['minutes'] * 60)
        - $date['seconds'];

}//end beginningOfWeek()

【讨论】:

  • 很棒的解决方案。开门见山。也适用于 PHP4。谢谢!
  • 此解决方案不支持时区,是吗?
  • 它使用服务器/脚本的默认时区。
  • 像 gmmktime() 获取 GMT 日期的 Unix 时间戳一样,getdate() 是否具有 GMT 日期的等价物?
  • 没有一个内置的,但是有很多examples in the comments on the PHP Manual page
【解决方案5】:

我使用以下sn-p的代码:

public static function getTimesWeek($timestamp) {

  $infos = getdate($timestamp);
  $infos["wday"] -= 1;
  if($infos["wday"] == -1) {
    $infos["wday"] = 6;
  }

  return mktime(0, 0, 0, $infos["mon"], $infos["mday"] - $infos["wday"], $infos["year"]);
}

【讨论】:

  • 如果当前日期在今年,但当前一周的第一天在上一年怎么办?
  • mktime() 照顾它。
【解决方案6】:

使用它来获取您想要的工作日的时间戳,而不是“星期六”写一周的第一天:

strtotime('Last Saturday',mktime(0,0,0, date('m'), date('d')+1, date('y')))

例如:在上面的代码中,您得到的是上周六的时间戳,而不是本周的周六。

请注意,如果现在是星期六,这将返回今天的时间戳。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 2016-10-24
    • 2010-12-26
    • 1970-01-01
    相关资源
    最近更新 更多