This is a short guide on how to get the day of the week from a given date string in PHP. This is useful for whenever you need to figure out what day a particular date fell on (or will fall on in the future). In this tutorial, I will be retrieving the textual day from a YYYY-MM-DD string.
The code is actually pretty simple:
<?php //Our YYYY-MM-DD date string. $date = "2002-12-02"; //Convert the date string into a unix timestamp. $unixTimestamp = strtotime($date); //Get the day of the week using PHP's date function. $dayOfWeek = date("l", $unixTimestamp); //Print out the day that our date fell on. echo $date . ' fell on a ' . $dayOfWeek;
An explanation of the code snippet above:
- We set our YYYY-MM-DD date string to “2002-12-02”. i.e. The 2nd of December, 2002.
- We converted our date string into a unix timestamp using PHP’s strtotime function.
- We then got the day of the week by giving the date function the “l” format and our unix timestamp. Note that the format for retrieving the full textual representation of the day of the week is a lowercase L – not a capital i.
- Finally, we printed out the day that our date fell on.
Of course, the code above can be shortened a bit:
<?php //Our YYYY-MM-DD date string. $date = "2012-01-21"; //Get the day of the week using PHP's date function. $dayOfWeek = date("l", strtotime($date)); //Print out the day that our date fell on. echo $date . ' fell on a ' . $dayOfWeek;
In the code above:
- I’ve changed the date string to “2012-01-21”. i.e. The 21st of January, 2012.
- I’ve combined lines 7 and 10 from the previous example into one line.
Note – if you want the three-letter representation of the day (“Mon” instead of “Monday”, etc), then you can simply change the date format from a lowercase L to a uppercase D.
Hopefully, you found this guide helpful! Other related articles:
- Calculate the difference between two dates.
- Get the first Monday of a month.
- Convert YYYY-MM-DD into DD-MM-YYYY.
- Calculate a person’s age.