Friday, October 19, 2012

Get first and last day of current month in PHP

To achieve this we need to create a DateTime object and then use the modify() method to change the timestamp as shown in the code snippet below.

<?php
// Create Object

$d = new DateTime( date("Y-m-d",strtotime('now') ) );

// Change the timestamp in 'd' object
$d->modify('first day of this month');

// Format the date according to FORMAT passed
echo $d->format('Y-m-d 00:00:00');

// Again change the timestamp in 'd' object
$d->modify('last day of this month');

// Format the last day of the month
echo $d->format('Y-m-d 23:59:59');
?>

The above code is quite self-explanatory. 

1. Php date() function takes timestamp as 2nd parameter and strtotime() reads the first parameter as a date and converts it to a timestamp.

2. The DateTime object's modify() method is used to alter the timestamp. It can accept various English-like strings like "+1 day", "-1 month", "first day of this month"


No comments: