How to Find/calculate the Day Number(Current) of the Year in PHP?

Problem:

There are 365 days in a year, so, every day has a number in the year. You want to find the day number of the current date of a specific date.

Solution:

You can find the day number of a date in few ways.

Method 1: Using date() function

To get the day number of the current date, follow the steps-·

  • Use “z” as formatting parameter in the date() function which will return day number.
  • Then add 1 to get the correct day number as it considers the 1st day of the year 0.

See the example-

<?php
echo date("z")+1;
?>

[wpdm_file id=147]

Output:
170

Note: The above output is based on 19th June 2014. You mau get different output if you’re on different date.

To get the day number of the any date, follow the steps-·

  • Use strtotime() function convert the date to its equivalent timestamp.·
  • Retrieve the day number of the timestamp using “z” as formatting parameter in the date function.
  • Then add 1 to get the correct day number as the formatting character “z” considers the 1st day of the year as 0.

See the example-

<?php
$timestamp = strtotime("19th June 2014");
echo date("z", $timestamp)+1;
?>

[wpdm_file id=148]

Output:
170

Method 2: Using DateTime class

PHP provides a ready made DateTime class to solve date time related issues quickly.
Using the DateTime class, we can get the day number of the current date in following steps-

  • Create an object of DateTIme() class which represents the current date.
  • Then, use format() method with formatting parameter “z” to return  the day number.

See the following example-

<?php
$date = new DateTime();
echo $date->format('z')+1;
?>

[wpdm_file id=149]

Output:
170

Using the DateTime class to get the day number of any date follow the steps below-

  • First we’ll create a DateTime object using createFromFormat with the date.
  • Then, use format() method with formatting parameter “z” to return  the day number.

See the following example-

<?php
$date = DateTime::createFromFormat('j-M-Y', '19-Jun-2014');
echo $date->format('z')+1;
?>

[wpdm_file id=150]

Output:
170

How it works:
In the example above, we tried to find the day number of 19th June 2014. As we’ll create a DateTime object from the date, in the first line, we used the date as second parameter as the matching formatting string in the first parameter. This is how cretaFromFormat() method works. Then, in the next line, we used format() method get the day number. As the formatting character “z” returns 0 for the first day, we added one to get the correct day number.