get_weekstartend()WP 0.71

Gets the timestamp of the start and end of the week to which the specified date belongs.

We pass the date in MySQL format to the function, and the function determines the week of that date and calculates when the week started and when it ended. The start day of the week can be specified in the second parameter.

1 time — 0.000049 sec (very fast) | 50000 times — 0.33 sec (very fast) | PHP 7.1.2RC1, WP 4.7.3

No Hooks.

Returns

Int[]. The function will return an array with keys start and end:

Array (
	[start] => 1488153600 // 2017 02 27 00:00:00
	[end]   => 1488758399 // 2017 03 05 23:59:59
)

Usage

get_weekstartend( $mysqlstring, $start_of_week );
$mysqlstring(string) (required)
Date or Date and time in MySQL format, for example: 2017-03-03 or 2017-03-03 15:08:08.
$start_of_week(int/string)

The day from which the week starts:

  • 1 - Monday.
  • 2 - Tuesday.
  • etc.

By default, it is taken from the option get_option( 'start_of_week' ).

Default: ''

Examples

0

#1 Get the start and end time of a week

Demonstration of the function works.

Let pass into the function the date 3 March 2017 which has a week starting with 27 Feb and ending with 5 March:

$arr = get_weekstartend( '2017-03-03' );

As a result, $arr will contain the following array

Array(
	[start] => 1488153600 // 2017-02-27 00:00:00 - Monday
	[end] => 1488758399 // 2017-03-05 23:59:59 - Sunday
)

Changelog

Since 0.71 Introduced.

get_weekstartend() code WP 6.8.3

function get_weekstartend( $mysqlstring, $start_of_week = '' ) {
	// MySQL string year.
	$my = substr( $mysqlstring, 0, 4 );

	// MySQL string month.
	$mm = substr( $mysqlstring, 8, 2 );

	// MySQL string day.
	$md = substr( $mysqlstring, 5, 2 );

	// The timestamp for MySQL string day.
	$day = mktime( 0, 0, 0, $md, $mm, $my );

	// The day of the week from the timestamp.
	$weekday = (int) gmdate( 'w', $day );

	if ( ! is_numeric( $start_of_week ) ) {
		$start_of_week = (int) get_option( 'start_of_week' );
	}

	if ( $weekday < $start_of_week ) {
		$weekday += 7;
	}

	// The most recent week start day on or before $day.
	$start = $day - DAY_IN_SECONDS * ( $weekday - $start_of_week );

	// $start + 1 week - 1 second.
	$end = $start + WEEK_IN_SECONDS - 1;

	return compact( 'start', 'end' );
}