PHP Date

Setting Timezone in PHP

Setting the timezone in php.ini

date.timezone = "America/Los_Angeles"
date.timezone = "UTC"

Set the timezone in PHP script


PHP generates the following warning if the timezone is not set before making PHP time or date functions

PHP Warning:  date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function.

Unix time

Get current Unix time in PHP


PHP mktime

Return an Unix time with mktime

int mktime($hour, $minute, $second , $month , $day, $year, $is_daylight_savings)
mktime(0, 0, 0, 12, 10, 2010);


int mktime ([ int $hour = date("H") [, int $minute = date("i") [, int $second = date("s")
            [, int $month = date("n") [, int $day = date("j")
            [, int $year = date("Y") [, int $is_dst = -1 ]]]]]]] )

PHP date

Returns a string represent a PHP date with a given format

string date ( string $format [, int $timestamp = time() ] )
  • if timestamp is missing, PHP uses the current time


date("Y/m/d");   // Generate the string "2010/02/05"
date("Y");   // Generate the string "2010"
date('Y-m-d H:i:s'); //2011-02-04 23:49:22

Get the String for tomorrow

$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));
$dateText = date("Y/m/d", $tomorrow);

MySQL Datetime and PHP Unix time

Conversion between PHP time and MySQL time

Convert a unix time to MySQL datetime

// Get current Unix time
$php_unix_time = time();

$mysqldate = date( 'Y-m-d H:i:s', $php_unix_time );

Convert a MySQL datetime to a unix time

$php_unix_time = strtotime( $mysqldate );

Conversion in the SQL

$query = "UPDATE table SET
    datetimefield = FROM_UNIXTIME($php_unix_time)
$query = "SELECT UNIX_TIMESTAMP(datetimefield)
    FROM table WHERE...";

Enter a String in SQL

SELECT pch_pc_id
FROM partner_campaign_history AS pch
WHERE pch.create_time >= STR_TO_DATE(?,'%m/%d/%Y') AND pch.create_time <= STR_TO_DATE(?,'%m/%d/%Y');