Need to find the timestamp for the first minute of the first day of the current week.
What is the best way to do this?
<?php
$ts = mktime(); // this is current timestamp
?>
Need to find the timestamp for the first minute of the first day of the current week.
What is the best way to do this?
<?php
$ts = mktime(); // this is current timestamp
?>
If Monday is your first day:
$ts = mktime(0, 0, 0, date("n"), date("j") - date("N") + 1);
If you think Monday is the first day of the current week...
$ts = strtotime('Last Monday', time());
If you think Sunday is the first day of the current week...
$ts = strtotime('Last Sunday', time());
If it is the monday you're looking for:
$monday = new DateTime('this monday');
echo $monday->format('Y/m/d');
If it is the sunday:
new DateTime('this sunday'); // or 'last sunday'
For further information about these relative formats, look here "PHP: Relative Formats"
First of all, date/time functions in PHP are really slow. So I try to call them a little as possible. You can accomplish this using the getdate()
function.
Here's a flexible solution:
/**
* 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()
Use this to get timestamp of which weekday you want, instead 'Saturday' write first day of the week:
strtotime('Last Saturday',mktime(0,0,0, date('m'), date('d')+1, date('y')))
for example: in above code you get timestamp of last saturday, instead of this week's saturday.
note that, if the weekday is Saturday now, this will return today time stamp.
I use the following snippet of code:
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"]);
}