A web developer in Jackson, NJ

Working With Dates and Times in PHP

Working with Dates and Times prior to PHP 5.2 meant using date(), strtotime(), and other date related functions sometimes in convoluted ways to get to the date(s) you were looking for. Fortunately with PHP 5.2 the DateTime() class were introduced. (DateTimeZone() was introduced as well but is not covered here). It was further enhanced in PHP with additionally methods as well as the new DatePeriod() and DateInterval() classes.

Getting Started

Before we get started I will link to the relevant pages in the PHP manual for the classes that we will be using here. All of these require running PHP 5.2 or newer. Make sure you check your version of PHP before using any of this code.

List all days in a month

1
2
3
4
5
6
7
8
9

$start=new DateTime('first day of this month');$end=new DateTime('first day of next month');$interval= DateInterval::createFromDateString('1 day');$period=new DatePeriod($start,$interval,$end);foreach($periodas$dt){echo$dt->format("l Y-m-d"). PHP_EOL;}