PHP timestamp - first day of the week

You 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 ?> 
+6
source share
6 answers

If Monday is your first day:

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

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 this week ...

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

If this is the Monday you are looking for:

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

If it is Sunday:

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

For more information on these relative formats, see PHP here : relative formats "

+5
source

First of all, date / time functions in PHP are very slow. Therefore, I am trying to name them as soon 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() 
+2
source

I am using the following code snippet:

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

Use this to get the timestamp of the day you want, and instead of โ€œSaturdayโ€ write the first day of the week:

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

for example: in the code above, you get the timestamp of the last Saturday, not this Saturday.

Please note that if the weekday is Saturday, this will return the current timestamp.

0
source

Source: https://habr.com/ru/post/911520/


All Articles