Home >Backend Development >PHP Tutorial >Summary of common php time function usage

Summary of common php time function usage

怪我咯
怪我咯Original
2017-06-28 10:52:296961browse

1. How to set the time zone:

After php5, you have to set the time zone yourself, either by modifying the settings of php.ini or modifying it in the code.

Set the time zone in PHP.INI

date.timezone = PRC

Set the time zone in code

1 date_default_timezone_set( 'Asia/Shanghai');//'Asia/Shanghai' Asia/Shanghai

2 date_default_timezone_set('Asia/Chongqing');//Asia/Chongqing' is "Asia/Chongqing"

3 date_default_timezone_set('PRC');//where PRC is "People's Republic of China"

4 ini_set('date.timezone', 'Etc/GMT-8');

5 ini_set('date.timezone','PRC');

6 ini_set( 'date.timezone','Asia/Shanghai');

7 ini_set('date.timezone','Asia/Chongqing');

2.php time function and usage:

checkdate: Verify the correctness of the date.

bool checkdate (int $month, int $day, int $year)

month value is from From 1 to 12, the value of Day is within the range of days that a given month should have, leap years have been taken into account; the value of year is from 1 to 32767.

date: Format the server's time.

string date ( string $format [, int $timestamp ] ): Returns a string generated by integer timestamp according to the given format string. If no timestamp is given, the local current time is used. In other words, timestamp is optional and the default value is time().

date("Y-m-d H:i:s", strtotime("-1 days")) //昨天此刻的时间,明天则是 "1 days",前天则是"-2 days";
date("Y-m-d H:i:s", strtotime("0 days")) //今天此刻的时间,等价于date("Y-m-d H:i:s")

U is replaced with the number of seconds since a starting time (like January 1, 1970).

Y is replaced with a 4-digit year number.
y is replaced Replace it with the 2-digit year number.
F Replace it with the full English name of the month.
M Replace it with the English abbreviation of the month.
m Replace it with the number of months.
z Replace it with January 1 of the current year The number of days since.
d Replace with the number of days.
l Replace with the full English name of the day of the week.
D Replace with the English abbreviation of the day of the week.
w Replace with the day of the week (number).
H is replaced with hours (24-hour format).
h is replaced with hours (12-hour format).
i is replaced with minutes.
s is replaced with seconds.
A is replaced with "AM" or "PM".
a is replaced with "am" or "pm".
S is replaced with an ordinal suffix, such as: "st", "nd", "rd", "th".

time: Get the UNIX timestamp of the current time.

int time ( void ) Returns the number of seconds since the Unix epoch (January 1, 1970 00:00:00 Greenwich Mean Time) to the current time.

$nextWeek = time() + (7 * 24 * 60 * 60);
// 7 days; 24 hours; 60 mins; 60secs
echo 'Now:       '. date('Y-m-d H:i:s') ."\n";
echo 'Next Week: '. date('Y-m-d H:i:s', $nextWeek) ."\n";
// or using strtotime():
echo 'Next Week: '. date('Y-m-d H:i:s', strtotime('+1 week')) ."\n";
echo 'Previous Week: '. date('Y-m-d H:i:s', strtotime('-1 week')) ."\n";//或者用strtotime('-7 day')

mktime: Get UNIX timestamp.

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 ]]]]]]] ) returns the Unix timestamp based on the given parameters. A timestamp is a long integer containing the number of seconds since the Unix epoch (January 1 1970 00:00:00 GMT) to a given time. If the parameter is illegal, this function returns FALSE (returns -1 before PHP 5.1).

$lastday = mktime(0, 0, 0, 3, 0, 2000);//括号里的参数分别表示 时分秒月天年
echo strftime("Last day in Feb 2000 is: %d", $lastday)."<br>";
$lastday = mktime(0, 0, 0, 4, -31, 2000);
echo strftime("Last day in Feb 2000 is: %d", $lastday);

Output:

Last day in Feb 2000 is: 29
Last day in Feb 2000 is: 29


##getdate: Get time and date information.

array getdate ([ int

$timestamp = time() ] )

$today = getdate();

var_dump($today);
Output:

array (size=11)
  &#39;seconds&#39; =>
int

 27
  &#39;minutes&#39; =>
int

 44
  &#39;hours&#39; =>
int

 8
  &#39;mday&#39; =>
int

 4
  &#39;wday&#39; =>
int

 3
  &#39;mon&#39; =>
int

 11
  &#39;year&#39; =>
int

 2015
  &#39;yday&#39; =>
int

 307
  &#39;weekday&#39; =>
string

 &#39;Wednesday&#39; (length=9)
  &#39;month&#39; =>
string

 &#39;November&#39; (length=8)
  0 =>
int

 1446597867

microtime: Gets the millionth of a second value of the UNIX timestamp of the current time.

mixed microtime ([ bool

$get_as_float ] ) If the $get_as_float parameter is given and its value is equivalent to TRUE, this function will return a floating point number.

function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

$time_start = microtime_float();

// Sleep for a while
usleep(10000000);//usleep — 以指定的微秒数延迟执行,10000000是10秒,sleep是延迟多少秒

$time_end = microtime_float();
$time = $time_end - $time_start;

echo "Did nothing in $time seconds\n";//Did nothing in 9.9999949932098 seconds

strftime: Format the server's time locally. http://php.net/manual/zh/function.strftime.php

gettimeofday: Get the current time. http://php.net/manual/zh/function.gettimeofday.php

gmdate: Get the time difference between the current time and GMT.

easter_date: Calculate Easter date.

easter_days: Calculate the number of days between Easter and March 21st.

gmmktime: Get the Greenwich Mean Time of a UNIX timestamp.

3. Supplement:

$_SERVER['REQUEST_TIME'] 是 PHP 内置的当前页面开始运行时的时间戳,在当前页面运行结束时将 time() - $_SERVER['REQUEST_TIME'] 得到的就是当前页面运行的时间(秒):

一天86400秒 

一周 86400*7=604800秒


set_time_limit用法:set_time_limit(秒数);规定从该句运行时起程序必须在指定秒数内运行结束, 超时则程序出错退出.



一个问题举例

$nowdate="1999-08-05" ;
$aa=getdate($nowdate);
$year=$aa[&#39;year&#39;];
$month=$aa[&#39;mon&#39;];
echo $year."</br>";
echo $month;

为何得到:

1970

1

我希望得到:

1999

8

如何解决?
--------------------------------------------------------------------------------

$nowdate="1999-08-05" ;
$aa=strtotime($nowdate);
$year=date("Y",$aa);
$month=date("n",$aa);
echo $year."</br>";
echo $month;

--------------------------------------------------------------------------------

$endtime="2004-09-09 18:10:00";
$d1=substr($endtime,17,2); //秒
$d2=substr($endtime,14,2); //分
$d3=substr($endtime,11,2); // 时
$d4=substr($endtime,8,2); //日
$d5=substr($endtime,5,2); //月
$d6=substr($endtime,0,4); //年

echo $d1.&#39;-&#39;.$d2.&#39;-&#39;.$d3.&#39;-&#39;.$d5.&#39;-&#39;.$d4.&#39;-&#39;.$d6."<br>";
echo date("Y-m-d H:i:s")."<br>";
$now_T=mktime(date("H"),date("i"),date("s"),date("m"),date("d"),date("Y"));
echo "此时的time".$now_T."<br>";
$now_S=mktime("$d3","$d2","$d1","$d5","$d4","$d6");
echo "2004-09-09 18:10:00时的time".$now_S."<br>";
$end_TS=($now_T-$now_S)/60;   //计算 剩余分钟
echo "相差".$end_TS."分";

输出

00-10-18-09-09-2004
2015-11-04 09:02:08
此时的time1446598928
2004-09-09 18:10:00时的time1094724600
相差5864572.1333333分


 




常用时间函数封装:


/**
 * 将秒数转换为时间(年、天、小时、分、秒)
 * @param int $time  秒数比如86400
 * @return bool|string
 */
public static function Sec2Time($time)
{
    if (is_numeric($time)) {
        $value = array(
            "years" => 0, "days" => 0, "hours" => 0,
            "minutes" => 0, "seconds" => 0,
        );
        if ($time >= 31556926) {
            $value["years"] = floor($time / 31556926);
            $time = ($time % 31556926);
        }
        if ($time >= 86400) {
            $value["days"] = floor($time / 86400);
            $time = ($time % 86400);
        }
        if ($time >= 3600) {
            $value["hours"] = floor($time / 3600);
            $time = ($time % 3600);
        }
        if ($time >= 60) {
            $value["minutes"] = floor($time / 60);
            $time = ($time % 60);
        }
        $value["seconds"] = floor($time);

        $t = $value["years"] . "年" . $value["days"] . "天" . " " . $value["hours"] . "小时" . $value["minutes"] . "分" . $value["seconds"] . "秒";

        return $t;

    } else {
        return (bool)FALSE;
    }

}

 

/**

 *当前日期是本月的第几周

 * @param int $date Y-m-d格式的时间,下同

 * @return int 

 

 * /

function weekOfMonth($date) {

    $firstOfMonth = strtotime(date("Y-m-01", strtotime ($date)));

    return intval(date("W", $date)) - intval(date("W", $firstOfMonth)) + 1;

}

 

//获取指定日期所在月的第一天和最后一天
function GetTheMonth($date)
{
    $firstday = date("Y-m-01", strtotime($date));
    $lastday = date("Y-m-d", strtotime("$firstday +1 month -1 day"));
    return array($firstday, $lastday);
}

//PHP获得指定日期所在星期的第一天和最后一天

function getdays($date )

{
    $lastday = date('Y-m-d', strtotime("$day Sunday"));
    $firstday = date('Y-m-d', strtotime("$lastday -6 days"));
    return array($firstday, $lastday);
}

/**

 * 获得指定日期的前/后$step(正负表示指定日期所在月的前后的第几个月份)个月的第一天和最后一天日期 

 * @param $date
 * @param $step
 * @return string
 */
function AssignTabMonth($date, $step)
{
    $date = date("Y-m-d", strtotime($step . " months", strtotime($date)));//得到处理后的日期(得到前后月份的日期)
    $firstday = date("Y-m-01", strtotime($date));
    $lastday = date("Y-m-d", strtotime("$firstday +1 month -1 day"));
    return array($firstday, $lastday);

}

 

$date = date('Ymd', strtotime($date));

$lastday = date('Ymd', strtotime("$date Sunday"));//周日

$firstday = date('Ymd', strtotime("$lastday -6 days"));//周一

 

$firstday = date('Ymd', strtotime(date('Y-m-01', strtotime($date))));//指定日期所在月的第一天

$lastday = date("Ymd", strtotime("$firstday +1 month -1 day"));//指定日期所在月的最后一天

$dayCount = $lastday - $firstday + 1; //间隔天数


mysql日期时间函数 http://www.jb51.net/article/23966.htm


The above is the detailed content of Summary of common php time function usage. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn