Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

How do i get a list of months names between two dates.

I would like to get a list of month names between two dates. How do I acchieve that?

Date1: 2015-10-10 Date2: 2016-11-11

thanks fΓΌr help

2 Answers

Emiliano Ceccon
Emiliano Ceccon
931 Points

Hi!

You can use the class "DateTime" to representing a date, in this case you would need two variables and that each one instantiate this class by passing as an argument the start (2015-10-10) and end date (2016-11-11). Then you establish a period instantiating the class "DateInterval", passing it the interval needed as an argument, in this case would be a month. As last configuration, you need to instantiate the class "DatePeriod", passing it as arguments, the start date, the interval and the end date. To access the dates you would use a foreach construct, and you would apply a date format using the "format" method.

I wrote an example to make it easier to understand (tested in PHP 5.4.x):

<?php

$startDate = new DateTime('2015-10-10');
$endDate = new DateTime('2016-11-11');

$dateInterval = new DateInterval('P1M');
$datePeriod   = new DatePeriod($startDate, $dateInterval, $endDate);

$monthCount = 0;

foreach ($datePeriod as $date) {
    echo "{$date->format('F')} ({$date->format('Y-m')})<br \>";

    $monthCount++;
}

echo "<br \>{$monthCount} months in total";

?>

If you run this example on the console, you should replace the HTML tag by the predefined constant "PHP_EOL" to indicate a new line, the code can be simplified, I wrote it in this way, lengthy, to make it more understandable, I leave the challenge to you!

You can get more information about how to treat with dates and times in PHP: Date and Time Related Extensions

I hope I've helpful to you!

thanks alot.