【发布时间】:2012-03-23 17:43:34
【问题描述】:
需要找到第一天的第一分钟的时间戳 >本周。
最好的方法是什么?
<?php
$ts = mktime(); // this is current timestamp
?>
【问题讨论】:
-
嗯,首先,您认为星期天还是星期一是一周的第一天?
需要找到第一天的第一分钟的时间戳 >本周。
最好的方法是什么?
<?php
$ts = mktime(); // this is current timestamp
?>
【问题讨论】:
如果星期一是你的第一天:
$ts = mktime(0, 0, 0, date("n"), date("j") - date("N") + 1);
【讨论】:
$ts = mktime(0, 0, 0, date("n"), date("j") - date("N"));
date("j") - date("N") + 1 产生的负数。
date("N") 更改为 date("w") 那么我想它也应该在 PHP4 中工作。
如果您认为星期一是本周的第一天...
$ts = strtotime('Last Monday', time());
如果您认为星期日是本周的第一天...
$ts = strtotime('Last Sunday', time());
【讨论】:
strtotime('Last Monday') 将返回一周前的星期一,而不是本周的开始(今天午夜)
如果您要查找的是星期一:
$monday = new DateTime('this monday');
echo $monday->format('Y/m/d');
如果是星期天:
new DateTime('this sunday'); // or 'last sunday'
有关这些相对格式的更多信息,请查看此处“PHP: Relative Formats”
【讨论】:
DateTime
首先,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()
【讨论】:
我使用以下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() 照顾它。
使用它来获取您想要的工作日的时间戳,而不是“星期六”写一周的第一天:
strtotime('Last Saturday',mktime(0,0,0, date('m'), date('d')+1, date('y')))
例如:在上面的代码中,您得到的是上周六的时间戳,而不是本周的周六。
请注意,如果现在是星期六,这将返回今天的时间戳。
【讨论】: