PHP时间戳 - 一周的第一天

时间:2012-03-23 17:43:34

标签: php datetime date time

需要为 第一天 第一分钟 找到时间戳 当前周

这样做的最佳方式是什么?

<?php

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

?>

6 个答案:

答案 0 :(得分:16)

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

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

答案 1 :(得分:7)

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

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

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

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

答案 2 :(得分:5)

如果是星期一,你正在寻找:

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

如果是星期天:

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

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

答案 3 :(得分:2)

首先,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()

答案 4 :(得分:0)

我使用以下代码片段:

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"]);
}

答案 5 :(得分:0)

使用它来获取您想要的工作日的时间戳,而不是周六&#39;写一周的第一天:

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

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

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

相关问题