You want to find out the week number from a date that you have.
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.
- Create a DateTime Object from your specific date
- Use the format() method to find out the week number using the “W” format character.
The following shows the code –
<?php $date = "2014-06-03"; $dateObj = new DateTime($date); $weekNumber = $dateObj->format("W"); echo "The week nummer of $date is: ". $weekNumber; ?>
The week number of 2014-06-03 is: 23
How it works:
|Line 2||The date with which we’ll work.|
|Line 3||We create a DateTIme object($dateObj) from the date.|
|Line 4||As 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 5||We prints the output.|
Method 2: Using strtotime() function
Using strtotime() to find out the week number is also 2 steps process-
- Convert your date to its equivalent timestamp. The timestamp of a date is number of seconds since January 1 1970 00:00:00 UTC.
- 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-
<?php $date = "2014-06-03"; $timestamp = strtotime($date); echo "The week nummer of $date is: " . date("W", $timestamp); ?>
The week nummer of 2014-06-03 is: 23