search
HomeBackend DevelopmentPHP TutorialSummary of common php time function usage

Summary of common php time function usage

Jun 28, 2017 am 10:52 AM
phpSummaryusage

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
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment