Monday, 13 August 2018

How to Calculate Week Number of the Year from a Specific Date in PHP?

Problem:

You want to find out the week number from a date that you have.

Solution:

You can find out week number from a date in few ways. Let’s see 2 of those-

Method 1: Using format() method of DateTime class from SPL.

Calculating week number from a date using DateTime class is 2 steps process.
  1. Create a DateTime Object from your specific date
  2. Use the format() method to find out the week number using the “W” format character.
The following shows the code –
1
2
3
4
5
6
<?php
$date = "2014-06-03";
$dateObj = new DateTime($date);
$weekNumber = $dateObj->format("W");
echo "The week nummer of $date is: ". $weekNumber;
?>
Output:The week number of 2014-06-03 is: 23
How it works:
Line 2The date with which we’ll work.
Line 3We create a DateTIme object($dateObj) from the date.
Line 4As we’re only interested in the week number, we use “W” in the format() method which will return the week number of the date that from the DateTIme object, $dateObj. We store the week number in the $weekNumber variable. Please note that the format() method accepts the format parameter strings that the date() method use. See the List of format characters.
Line 5We prints the output.

Method 2: Using strtotime() function

Using strtotime() to find out the week number is also 2 steps process-
  1. Convert your date to its equivalent timestamp. The timestamp of a date is number of seconds since January 1 1970 00:00:00 UTC.
  2. From the timestamp, we’ll find out the week number using date() function with “W” format string. The format character “W” returns the week number of year.
See the following example-
1
2
3
4
5
<?php
$date = "2014-06-03";
$timestamp = strtotime($date);
echo "The week nummer of $date is: " . date("W", $timestamp);
?>
Output:The week nummer of 2014-06-03 is: 23

0 comments:

Post a Comment