Mktime() - Timestamp yesterday, last month, etc.)
Intro
The mktime()function allows the return of the UNIX timestamp of a given date, ie the number of seconds elapsed between 1 January 1970 and a specific date.
However, in its current usage, it is usually necessary to define two timestamps for a certain period.
Note that to convert the timestamps below dated MySQL (DATETIME), just use the date function as follows:
<?
$mysql_datetime = date('Y-m-d H:i:s',$timestamp);
?>
Below are the mostly used examples:
Last 24 hours
The code below covers the past 24 hours so far:
<?php
$startTime = mktime() - 24*3600;
$endTime = mktime();
?>
Yesterday
The code below works even if you are the 1st of the month or the 1st January of the year. It covers the period from yesterday at 00:00:00 to 23:59:59 yesterday:
<?php
$startTime = mktime(0, 0, 0, date('m'), date('d')-1, date('Y'));
$endTime = mktime(23, 59, 59, date('m'), date('d')-1, date('Y'));
?>
This week
The code below is assumed that the first day of the week is Monday. It covers the period from Monday morning at 00:00:00 to now:
<?
$startTime = mktime(0, 0, 0, date('n'), date('j'), date('Y')) - ((date('N')-1)*3600*24);
$endTime = mktime();
?>
Last week
The code below is assumed that the first day of the week is Monday. It covers the period from Monday(15 day before) at 00:00:00 to next Sunday at 23:59:59:
<?
$startTime = mktime(0, 0, 0, date('n'), date('j')-6, date('Y')) - ((date('N'))*3600*24);
$endTime = mktime(23, 59, 59, date('n'), date('j'), date('Y')) - ((date('N'))*3600*24);
?>
This Month
The code below covers the period from 1 month to now (current month):
<?
$startTime = mktime(0, 0, 0, date('m'), 1, date('Y'));
$endTime = mktime();
?>
Last 30 days (last 30 days)
The code below covers the period from 30 days ago to now:
<?
$ starttime = mktime () - 30 * 3600 * 24;
$ endTime = mktime ();
>
Last month
The code below covers the period from last month:
<?
$startTime = mktime() - 30*3600*24;
$endTime = mktime();
?>
Current year(this year)
The code below covers the period from January 1st to now at 00:00:00:
<?
$startTime = mktime(0, 0, 0, 1, 1, date('Y'));
$endTime = mktime();
?>
Last year (last year)
The code below covers the previous year, from January 1, at 00:00:00 to 31 December at 23:59:59:
<?
$startTime = mktime(0, 0, 0, 1 , 1, date('Y')-1);
$endTime = mktime(23, 59, 59, 12, 31, date('Y')-1);
?>