Wednesday, 8 August 2018

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:
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:
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.

0 comments:

Post a Comment