Home php教程 php手册 PHP笔记之:日期函数的使用介绍

PHP笔记之:日期函数的使用介绍

Jun 13, 2016 am 11:54 AM
php introduce use function it powerful date yes most of notes language

介绍
 
  PHP是一门非常令人惊奇的语言。它足够强大(最大的博客(wordpress)的核心语言),它足够广泛(运行在最大社交网站facebook上),它足够简单(作为初学者首选入门语言)。在低成本的机器上运行良好。而且php语言有很多非常不错的服务器套件(如WAMP和MAMP),很方便的安装在你的机器上。PHP有非常丰富的库资源,便于开发者很容易的处理一些业务。由于我们在项目中与日期接触最多,所以今天就从日期函数入手学习。

举一个简单的date例子
 
我将使用echo命令把内容输出到我们的客户端(浏览器)。我将使用下面的代码做为基础代码。

复制代码 代码如下:





   
    Getting started with dates in php5


date_default_timezone_set('Asia/Shanghai');
echo "Today is ",date('l');
?>



 你将在你的浏览器里看到如下的内容。

Today is Friday这个函数输出星期几的文本格式。date函数至少需要一个字符参数(这个参数告诉我们怎样格式化当前日期)。

尝试不同的格式
 
如果你看了php手册中PHP date function,那么你将发现有很多格式化日期的方式。



将得到

Today is 2012-08-17

有一些日期是很普遍地被使用,所以PHP提供了一些常量供你使用。举例,你可以使用Cookie获取到客户端日期。

 你将得到如下面的内容

Today is Friday, 17-Aug-12 11:34:38 CST注意当使用常量的时候不要使用引号。


现在是什么时候?
 
如果你想要输出当前时间,你能使用date(不同格式化字符参数)。

 你将得到

The time is 11:39:59am

本地化你的时区
 
如果你发现以上的代码没有给出正确的时间,很有可能是因为你的服务器设置了与你本地不同的时区。你需要在服务器上指定时区,那么你用下面的代码:

 

 这个将设置中国上海时区。这是php5的函数(注意旧版本的php),有很多供你选择时区。如果你想永久生效,你可以修改你的php.ini文件。

获取其他时间
 
你经常需要其他时间,而不是现在的时间。当你用date()函数创建时间的时候,系统会使用Unix系统时间。这个时间表示从1970年1月1日 00:00:00 GMT(Unix 纪元时间),到现在的秒数。

为了详细说明怎样获取指定时间的日期,你可以提供秒数做为date(0函数的第二个参数。

结果是:

Today is 2011-06-27

这个看起来没什么用途,但它意味着你能用date()函数做计算。这之前,你需要简单的创建一个时间戳。

创建时间戳
 
有很多创建时间戳的方式。我们能够使用mktime()函数得到我们需要的时间戳。

复制代码 代码如下:


    $mytime=mktime(9, 23, 33, 6, 26, 2011);
    echo "Today is ",date('Y-m-d g:i:sa', $mytime);
?>


得到的结果是:

Today is 2011-06-26 9:23:33am mktime()

函数需要你依次传递小时,分钟,秒,月,日,年。这是获取时间戳的好的方式,但是有更酷的方式。

通过字符获取时间戳
 
你可以使用strtotime()函数获取时间戳,php把可读的字符转换成Unix时间戳。PHP在把字符转换成时间戳方面是相当灵活的,因此你可以插入各种各样的值来获取你想要的时间戳。

这是一个简单例子:

复制代码 代码如下:


    $mytime=strtotime("7:50pm June 26 2011");
    echo "Today is ",date('Y-m-d g:i:sa', $mytime);
?>


输出:

Today is 2011-06-26 7:50:00pm

PHP在解释字符方面是相当灵巧的,但不是完美的,因此,在你插入之前一定要测试你输入的字符。使用"english-like instructions"转化成需要的时间戳,这是一个非常不错的方式。你可以像下面这样做:

复制代码 代码如下:


$nextfriday=strtotime("next Friday"); //下周五
$nextmonth=strtotime("+1 Month"); //从今天开始计算一个月以后的时间
$lastchristmas=strtotime("-1 year dec 25"); //去年圣诞节


获取日期范围
 
strtotime返回的值被转换为数字,我们能够用这些数字做基础运算,我们可以用这些数字做很多非常有意思的事情。比如,你每周二需要教一门功课,为期16周,你想得到你教科时间。你能够做下面的事情。

复制代码 代码如下:


$startdate = strtotime('next Tuesday');
$enddate = strtotime('+16 weeks', $startdate);
$currentdate = $startdate;
echo '

    ';
    while($currentdate     echo "\t
  1. ", date('M d', $currentdate);
        $currentdate = strtotime('+1 week', $currentdate);
    endwhile;
    echo '
';
?>

你将会得到如下的结果:

复制代码 代码如下:


Aug 21
Aug 28
Sep 04
Sep 11
Sep 18
Sep 25
Oct 02
Oct 09
Oct 16
Oct 23
Oct 30
Nov 06
Nov 13
Nov 20
Nov 27
Dec 04


注意一下这行:$currentdate = strtotime("+1 week", $currentdate)。在这行,你会发现你需要指定一个时间戳做为第二个参数,strtotime将使用这个参数代替默认时间戳(今天),并进行运算。

到某一个日期的天数
 
使用计算器的时候,我们会试图去计算到某一天的天数。你很容易计算11月份第四个星期四的时间戳。

复制代码 代码如下:


$someday = strtotime("3 weeks thursday November 1");
$daysUtilDate = ceil(($someday - time())/60/60/24);
echo "There are ", $daysUtilDate, " until Thanksgiving";


首先,我们开始计算感恩节日期(11月1号之后的第一个星期四之后的第3个星期四),然后我们通过简单的算术,计算出感恩节到当前时间之间的天数。当我们进行比较运算的时候,我们可以使用time(),因为它返回,到当前时间的纪元秒数。
Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles