[英]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.