Tuesday 14 August 2018

How to Find the Day of the Week from a Date in PHP?

Problem:

You want to find out the day of a given date ex. 11th September 2001.

Solution:

There is more than one way to find out day of the week of a given date. Let’s see few of those methods-

Method 1: Using SPL

Using SPL(standard PHP Library), you can find out week day from a given date very easily.
If you didn’t use before, PHP provides some classes (which is called SPL in a whole) to help developers solve most common problem very easily. One of those classes is DateTIme class. We’ll use this class.
See the following example-
1
2
3
4
<?php
$dateObj = DateTime::createFromFormat('M-j-Y', 'Sep-11-2001');
echo $dateObj->format('l');
?>
Output:Tuesday
How it works:
Line 2Here, we use createFromFormat() method of the DateTime class to create a DateTime object using the  supplied date(Sep-11-2001 which is mentioned in the second parameter) according to the specified format(specified in first parameter). And, we store that DateTime object in the $dateObj variable.
Line 3Here, we use another method of DateTime class- format(). This method returns a formatted date according to the format specified in its parameter. As we want to know the day of the week from our DateTIme object($dateObj), we mention ‘l’ as parameter which returns day of the week; here, Tuesday.

Method 2: Using date() function

Using date() function you can also calculate the day of the week from a date. At first, you have to convert the supplied date to unix timestamp, then, find the day of the week using date() function.
See the following code-
1
2
3
4
<?php
$timestamp = strtotime("11 September 2001");
echo $formattedDate = date("l", $timestamp);
?>
Output:Tuesday
How it works:
Line 2strtotime() function returns unix timestamp equivalent to the date, 11 september 2001. Note: this function can take any English textual datetime and returns its equivalent unix timestamp.
Line 3The date() function returns the day of the week(‘l’ in the first parameter tells to returns day of the week from the $timestamp timestamp) of the date represted by the $timestamp.

0 comments:

Post a Comment