Jump to: navigation, search

PHP Date

From w3cyberlearnings

Contents

today

Today 2012-02-14

 <?php
      echo 'Today '. date('Y-m-d');
 <?

get the last day of the current month

<?php
 $last_day_of_the_month = date('t',  strtotime('today'));
 echo $last_day_of_the_month;
?>

get the last day of the any month

<?php
 $last_day_of_next_month = date('t', strtotime('2/1/2012'));
 echo $last_day_of_next_month;
?>

get the last day of the last month

<?php
$last_day_of_last_month = date('t', strtotime('last month'));
echo $last_day_of_last_month;
?>

get the last day of next month

<?php
 $last_day_of_next_month = date('t', strtotime('next month'));
 echo $last_day_of_next_month;
?>

alternative way get the last day of the month

This is more flexible that the above methods, because you don't need to check the date. Everything will be dynamic adjust to the date and year accordingly.

<?php
   $month = date('m')-2;
   $last_day_of_last_month = date('Y-m-t', mktime(0,0,0,$month,1,2012));
   echo $last_day_of_last_month;
?>

get the date range for previous month

  • This is not the best method, but it is working.
<?php

$current_month = intval(date('m'));
$year = date('Y');
$last_month = null;

if ($current_month == 1) {
    $last_month = 12;
    $year = intval($year - 1);
} else {
    $last_month = intval($current_month - 1);
}


$mydate = strtotime("$year-$last_month-01");
$day = date('t', $mydate);

$first_date_of_month = "{$year}-{$last_month}-1";
$laste_date_of_month = "{$year}-{$last_month}-{$day}";

echo $first_date_of_month . '<br/>';
echo $laste_date_of_month . '<br/>';
?>

Display Result

2012-1-1
2012-1-31

a better way to get current date range (start-->end date)

<?php
$month = date('m');
$year = date('Y');
$start_of_month = date('Y-m-d', mktime(0,0,0,$month,1,$year));
$last_of_month = date('Y-m-t', mktime(0,0,0,$month,1,$year));

echo $start_of_month . '--->'. $last_of_month;
?>

Display Result

2012-02-01--->2012-02-29

a better eay to get the past date range (start-->end date)

Subtract 2 months from the current month.

<?php
$month = date('m')-2;
$year = date('Y');
$start_of_month = date('Y-m-d', mktime(0,0,0,$month,1,$year));
$last_of_month = date('Y-m-t', mktime(0,0,0,$month,1,$year));

echo $start_of_month . '--->'. $last_of_month;
?>

Display Result

2011-12-01--->2011-12-31

a better way to get furture date range (start--->end date)

Add 5 months to the current month.

<?php
$month = date('m')+5;
$year = date('Y');
$start_of_month = date('Y-m-d', mktime(0,0,0,$month,1,$year));
$last_of_month = date('Y-m-t', mktime(0,0,0,$month,1,$year));

echo $start_of_month . '--->'. $last_of_month;
?>

Display Result

2012-07-01--->2012-07-31

Navigation
Web
SQL
MISC
References