search
HomeBackend DevelopmentPHP TutorialA bunch of date and time operations in php

A bunch of date and time operations in php

Jun 06, 2019 am 11:47 AM
php date time

A bunch of date and time operations in php

下载 (1).jpg

Format date and time

date : Format Date and time

  • Scenario

Format the current date and time or a specific date and time ##The output is a string in a specific format, often used for humanized display of information.

  • Description

Return to Date and time string generated after formatting a certain timestamp. If no timestamp is given, the local current time will be used by default.

  • Remarks

FormatDescriptionReturn value example##y219##M##m01 to 12The day of the week, the text indicates, The day of the month, hour, hour, Whether it is daylight saving time, otherwise it is minutes with leading zeros Number The English suffix after the number of days in a month, 2st,nd,rdj Number of seconds, with leading zeros ##
  • Common formats

// 形如 2019-05-31 12:00:00echo date("Y-m-d H:i:s");
// 形如 2019/05/31 12:00:00echo date("Y/m/d H:i:s");
// 形如 2019年05月31日 12时00分00秒echo date("Y年m月d日 H时i分s秒");
  • Examples

<?php
// 设置当前时区为上海时区
date_default_timezone_set("Asia/Shanghai");

// 获取当前时区 : Asia/Shanghai
echo "当前时区 : ".date_default_timezone_get()."<br/>";

// `Y年m月d日 H时i分s秒` 格式化当前时间 : 2019年05月30日 22时32分46秒
echo "当前时间 : ".date("Y年m月d日 H时i分s秒")."<br/>";

// `Y-m-d H:i:s` 格式化当前时间 : 2019-05-30 22:32:46
echo "当前时间 : ".date("Y-m-d H:i:s")."<br/>";

// `w` 星期中的第几天,数字表示: 0(表示星期天)到 6(表示星期六)
switch (date("w")) {    
    case &#39;0&#39;:
        $dayStr = "日";        
        break;    
    case &#39;1&#39;:
    $dayStr = "一";        
    break;    
  case &#39;2&#39;:
    $dayStr = "二";        
    break;    
  case &#39;3&#39;:
    $dayStr = "三";      
    break;   
  case &#39;4&#39;:
    $dayStr = "四";        
    break;    
  case &#39;5&#39;:
    $dayStr = "五";        
    break;    
  case &#39;6&#39;:
    $dayStr = "六";        
    break;    
  default:
    $dayStr = "未知";        
    break;
} 
// 2019年05月30日 星期四
echo "当前时间 : ".date("Y年m月d日")." 星期".$dayStr."<br/>";
echo "<hr/>";

// `z` 年份中的第几天 : 今天是全年的第149天
echo "今天是全年的第".date("z")."天<br/>";

// `W` ISO-8601 格式年份中的第几周,每周从星期一开始 : 本周是全年的第22周
echo "本周是全年的第".date("W")."周<br/>";

// `t` 指定的月份有几天 : 本月共有31天
echo "本月共有".date("t")."天<br/>";
?>

Date conversion timestamp

time: Returns the current Unix timestamp

  • Scenario

Get the timestamp of the current date and time or a specific date and time, often used for conversion between dates and times.

  • Description

Returns the current time since the Unix epoch (January 1, 1970 00:00:00 GMT) The number of seconds.

  • Example

<?php
// 设置当前时区为上海时区
date_default_timezone_set("Asia/Shanghai");

// 获取当前时区
echo "当前时区 : ".date_default_timezone_get()."<br/>";

// 一周前的日期时间: 7 days; 24 hours; 60 mins; 60 
secs$preWeek = time() - (7 * 24 * 60 * 60);
echo "现在是".date("Y-m-d H:i:s").",上周是".date("Y-m-d H:i:s",$preWeek)."<br/>";

// 一周后的日期时间: 7 days; 24 hours; 60 mins; 60 secs
$nextWeek = time() + (7 * 24 * 60 * 60);
echo "现在是".date("Y-m-d H:i:s").",下周是".date("Y-m-d H:i:s",$nextWeek)."<br/>";
?>

microtime : Returns the current Unix Timestamp and microseconds

  • Scenario

Get the time of the current date-time or a specific date-time Stamp, often used for point analysis of program running process, and can also be used for conversion between dates and times.

  • Explanation

The current Unix timestamp and microseconds. This function is only available under operating systems that support the `gettimeofday()`` system call.

  • ##Example

  • <?php
    
    // 设置当前时区为上海时区
    date_default_timezone_set("Asia/Shanghai");
    
    // 获取当前时区
    cho "当前时区 : ".date_default_timezone_get()."<br/>";
    
    // 当前日期时间戳
    echo "当前日期时间戳: ".time()." <--> ".microtime()." <--> ".microtime(TRUE)."<br/>";
    
    ?>
mktime: Get the Unix timestamp of a date

  • ##Scenario

  • Get the timestamp of a given date, parse it in sequence according to the "hour, minute, second, month, day and year" format, and return the timestamp.

  • Description

  • Return the Unix timestamp according to the given parameters.

  • Remarks

Y 4 Complete year with digits 2019
Year represented by digits
Three-letter abbreviation for the month Jan to Dec
The month represented by the number, with leading zeros # #D
3 letters Mon to Sun d
2 digits with leading zeros 01 to 31 H
24 hour format, with leading zeros 00 to 23 h
12 hour format, with leading zeros 01 to 12 I
If so Daylight saving time is 10 ##i
00 to 59 S
characters or th, can be used together with s
00 to 59
FormatHhour00 to 23##i Minutes ##sday01 to 31year Year number, can be two or four digits corresponds to corresponds to
Description Parameter example
Number of hours
minute 00 to 59
second Number of seconds 00 to 59 # #n
month Number of months 01 to 12 ## j
Number of days ##Y
0-692000-2069 ,70-1001970-2000<blockquote><p>格式: 时分秒 月日年,支持从右往左依次省略,被省略的值取当前时间的对应值.<br></p></blockquote> <ul style="list-style-type: disc;"><li><p><strong>示例</strong></p></li></ul><pre class='brush:php;toolbar:false;'>&lt;?php // 设置当前时区为上海时区 date_default_timezone_set(&quot;Asia/Shanghai&quot;); // 获取当前时区 echo &quot;当前时区 : &quot;.date_default_timezone_get().&quot;&lt;br/&gt;&quot;; // 指定日期时间戳: 时分秒 月日年 : 1559275200 &lt;--&gt; 2019-05-31 12:00:00 echo &quot;2019年05月31日 12:00:00 的时间戳: &quot;.mktime(12,0,0,5,31,2019).&quot; &lt;--&gt; &quot;.date(&quot;Y-m-d H:i:s&quot;, mktime(12,0,0,5,31,2019)).&quot;&lt;br/&gt;&quot;; // 距离国庆节还有多少天,单位秒 : 今天是2019-05-31,距离国庆节还剩122天 $nationalDay = mktime(0,0,0,10,1,2019); $currentDay = time(); $remainingDay = floor(abs($nationalDay - $currentDay)/(24*3600)); echo &quot;今天是&quot;.date(&quot;Y-m-d&quot;).&quot;,距离国庆节还剩&quot;.$remainingDay.&quot;天&lt;br/&gt;&quot;; ?&gt;</pre><blockquote><p>strtotime : 将任何字符串的日期时间描述解析为 Unix 时间戳</p></blockquote> <ul style="list-style-type: disc;"><li><p><strong>场景</strong></p></li></ul> <p>将英文日期解析成时间戳,比直接解析日期方便,采用自然语义而不是编程语言进行转换日期.</p> <ul style="list-style-type: disc;"><li><p><strong>说明</strong></p></li></ul> <p>本函数预期接受一个包含<strong>美国英语日期格式</strong>的字符串并尝试将其解析为 Unix 时间戳(自 January 1 1970 00:00:00 GMT 起的秒数,其值相对于 now 参数给出的时间,如果没有提供此参数则用系统当前时间.</p> <ul style="list-style-type: disc;"><li><p><strong>常用格式</strong></p></li></ul><pre class='brush:php;toolbar:false;'>// 2019-06-02 echo date(&quot;Y-m-d&quot;, strtotime(&quot;2019-05-31 +2 days&quot;)); // 2019-07-01 echo date(&quot;Y-m-d&quot;, strtotime(&quot;2019-05-31 +1 month&quot;)); // 2019-06-09 echo date(&quot;Y-m-d&quot;, strtotime(&quot;2019-05-31 +1 week 2 days 4 hours 2 seconds&quot;));</pre><ul style="list-style-type: disc;"><li><p><strong><span style="font-size: 14px;">示例</span></strong></p></li></ul><pre class='brush:php;toolbar:false;'>&lt;?php // 设置当前时区为上海时区 date_default_timezone_set(&quot;Asia/Shanghai&quot;); // 获取当前时区 echo &quot;当前时区 : &quot;.date_default_timezone_get().&quot;&lt;br/&gt;&quot;; // 当前日期时间戳 echo &quot;当前日期时间戳: &quot;.time().&quot; &lt;--&gt; &quot;.strtotime(&quot;now&quot;).&quot; &lt;--&gt; &quot;.date(&quot;Y-m-d H:i:s&quot;, strtotime(&quot;now&quot;)).&quot;&lt;br/&gt;&quot;; // 一周后的日期时间: 7 days; 24 hours; 60 mins; 60 secs $nextWeek = time() + (7 * 24 * 60 * 60); echo &quot;现在是&quot;.date(&quot;Y-m-d H:i:s&quot;).&quot;,下周是&quot;.date(&quot;Y-m-d H:i:s&quot;,$nextWeek).&quot; &lt;--&gt; &quot;.date(&quot;Y-m-d H:i:s&quot;,strtotime(&quot;+1 week&quot;)).&quot;&lt;br/&gt;&quot;; echo &quot;现在是&quot;.date(&quot;Y-m-d H:i:s&quot;).&quot;,1周2天4小时2秒是&quot;.date(&quot;Y-m-d H:i:s&quot;,strtotime(&quot;+1 week 2 days 4 hours 2 seconds&quot;)).&quot;&lt;br/&gt;&quot;; echo &quot;现在是&quot;.date(&quot;Y-m-d H:i:s&quot;).&quot;,下周三是&quot;.date(&quot;Y-m-d H:i:s&quot;,strtotime(&quot;next Thursday&quot;)).&quot;&lt;br/&gt;&quot;; ?&gt;</pre><p><span style="font-size: 14px;"></span><br></p> <p><span style="font-size: 24px;"><strong>日期时间函总结</strong></span></p> <p>日期时间函数库是 php 内置的函数库,默认情况下已启用,值得注意的是,日期时间和时区有关,建议首先设置下时区.</p> <p>纵观日期时间的操作方法,总的来说,可以大致分为两类,一类是给计算机用的,另一类是给人看的.</p> <ul style="list-style-type: disc;"><li><p><strong>给人看的</strong></p></li></ul> <p><strong>date_default_timezone_set("Asia/Shang</strong><strong>hai") : 设置当前脚本使用的时区date("Y-m-d H:i:s") : 格式化日期时间date("Y-m-d", strtotime("2019-05-31 +2 days")) : 格式化英文描述的日期时间</strong></p> <ul style="list-style-type: disc;"><li><p><strong>给计算机用的</strong></p></li></ul> <p><strong>time() : 当前时间的秒数microtime() : 当前时间的秒数和微秒数strtotime() : 将字符串形式的日期时间转换成时间戳</strong></p> <p>最后,文档那么齐全,不懂就去多看看,忘记有啥方法全靠 ide 智能提示就好,多用用就会慢慢熟练。</p> <p>推荐教程:<a href="http://www.php.cn/course/888.html" target="_self">PHP制作阴阳历转换的日历插件</a></p>

The above is the detailed content of A bunch of date and time operations in php. 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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

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.

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

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.