PHP: Get the day of the week from a date string.

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:

  1. We set our YYYY-MM-DD date string to “2002-12-02”. i.e. The 2nd of December, 2002.
  2. We converted our date string into a unix timestamp using PHP’s strtotime function.
  3. 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.
  4. 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:

  1. I’ve changed the date string to “2012-01-21”. i.e. The 21st of January, 2012.
  2. 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: