Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.