Codxplore.com

Latest news:

Sahih al-Bukhari (সহীহ বুখারী) is a free Hadith application for android. This application is advertisement free. Download now https://play.google.com/store/apps/details?id=com.akramhossin.bukharisharif

Usages of PHP date, strtotime and mktime functions


Usages of PHP date, strtotime and mktime functions

To customize date and time PHP provides us some important functions such date, strtotime and mktime. In this post i will demonstrate some usages for these

functions.

Example 1:

Get year start and end date for the current year we can use

$yearStart = date("Y-m-d", strtotime('this year January 1st'));

$yearEnd = date("Y-m-d", strtotime("this year December 31st"));

Example 2:

Get month start and end date for the current month

$monthStart = date("Y-m-d", strtotime('first day of this month'));
$monthEnd = date("Y-m-d", strtotime("last day of this month"));

Example 3:

Get previous month start and end date

$lastMonthStart = date("Y-m-d", strtotime('first day of last month'));
$lastMonthEnd = date("Y-m-d", strtotime("last day of last month"));

Example 4:

Get week start and end date

$weekStart = date("Y-m-d", strtotime('monday this week'));
$weekEnd = date("Y-m-d", strtotime("sunday this week"));

Example 5:

get the first and last days of a given month

$query_date = '2010-02-04';
echo date('Y-m-01', strtotime($query_date));
echo date('Y-m-t', strtotime($query_date));

Example 6:

Displaying the list of months using mktime for the year 

for ($m=1; $m<=12; $m++) {
 $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
 echo $month;
}

Example 7:

run foreach loop between 2 given dates

$begin = new DateTime( '2010-05-01' );
$end = new DateTime( '2010-05-10' );
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);

foreach ($period as $dt){
  echo $dt->format( "l Y-m-d H:i:s\n" );
}

Tags : PHP,

Views : 2730

Subscribe Us


Follow Us