繁体   English   中英

PHP 时间戳 - 一周的第一天

[英]PHP timestamp - first day of the week

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

做这个的最好方式是什么?

<?php

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

?>

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

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

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

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

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

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

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

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

如果是星期天:

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

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

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

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

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

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

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

我使用以下代码片段:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM