PHP如何使用strtotime()函数实现时间转换?示例

2021年3月28日15:41:41 发表评论 1,023 次浏览

strtotime()函数是PHP中的内置函数, 用于将英语文本日期时间描述转换为UNIX时间戳。该函数接受英语的字符串参数, 该字符串参数表示日期时间。例如, "现在"指的是英语日期时间描述中的当前日期。该函数以秒为单位返回自Unix时代。我们可以使用date()函数以日期格式返回英文文本日期时间。

语法如下:

strtotime ($EnglishDateTime, $time_now)

参数:该函数接受如上所示和以下所述的两个参数:

  1. $ EnglishDateTime–此参数指定英文文本日期时间描述, 表示要返回的日期或时间。该函数解析字符串, 并以秒为单位返回时间。该参数是强制性的
  2. $ time_now此参数指定用于计算返回值的时间戳。它是一个可选参数。

注意:由于时间/日期不是固定的, 因此输出将有所不同。

下面的程序说明了strtotime()函数。

程序1:

下面的程序演示了strtotime()

当英文文本为" now"时起作用。

<?php
// PHP program to demonstrate the strtotime() 
// function when the english text is "now"
  
// prints current time in second 
// since now means current 
echo strtotime ( "now" ), "\n" ; 
  
// prints the current time in date format 
echo date ( "Y-m-d" , strtotime ( "now" )). "\n" ;
?>

输出如下:

1525378260
2018-05-03

程式2:

下面的程序演示了strtotime()

英文文本为日期时的功能。

<?php
// PHP program to demonstrate the strtotime() 
// function when the english text is a date
  
// prints the converted english text in second 
echo strtotime ( "12th february 2017" ), "\n" ; 
  
// prints the above time in date format 
echo date ( "Y-m-d" , strtotime ( "12th february 2017" )). "\n" ;
?>

输出如下:

1486857600
2017-02-12

程式3:

下面的程序演示了strtotime()

英文文本对应于任何一天时的功能。

<?php
// PHP program to demonstrate the strtotime() 
// function when the english text corresponds to any 
// day 
  
// prints the converted english text in second 
echo strtotime ( "next sunday" ), "\n" ; 
  
// prints the above time in date format 
echo date ( "Y-m-d" , strtotime ( "next sunday" )). "\n" ;
?>

输出如下:

1525564800
2018-05-06

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: