欢迎访问宙启技术站
智能推送

PHP日期时间函数示例

发布时间:2023-06-18 22:19:26

PHP 日期和时间函数在Web开发中非常普遍使用,它们允许您对日期和时间进行各种操作,例如格式化,比较,计算等等。在本文中,我们将讨论一些基本的PHP日期和时间函数示例,以帮助您更好地理解这些函数。

1. date()函数

date()函数是PHP中最常用的日期函数之一,它可用于格式化一个日期字符串。

以下是一些常见的日期格式:

- Y:四位数年份,例如2021

- m:月份(01-12)

- d:天数(01-31)

- h:小时(01-12)

- i:分钟(00-59)

- s:秒数(00-59)

- a:am或pm

以下是一个简单的示例,演示如何使用date()函数来获取当前日期和时间:

$current_date = date('Y-m-d');
$current_time = date('h:i:s a');

echo "Today's date is ".$current_date;
echo "<br>";
echo "Current time is ".$current_time;

输出:

Today's date is 2021-08-05
Current time is 01:30:10 pm

2. strtotime()函数

strtotime()函数可以将一个日期字符串转换为UNIX时间戳(自1970年1月1日以来的秒数)。

以下是一个简单的示例,演示如何使用strtotime()函数将一个日期字符串转换为UNIX时间戳:

$date_string = "2021-08-05";
$timestamp = strtotime($date_string);

echo "The UNIX timestamp for ".$date_string." is ".$timestamp;

输出:

The UNIX timestamp for 2021-08-05 is 1628102400

3. time()函数

time()函数用于获取当前的UNIX时间戳。

以下是一个简单的示例,演示如何使用time()函数来获取当前时间的UNIX时间戳:

$current_timestamp = time();

echo "The current UNIX timestamp is ".$current_timestamp;

输出:

The current UNIX timestamp is 1629131463

4. mktime()函数

mktime()函数可用于创建一个日期的UNIX时间戳。

以下是一个简单的示例,演示如何使用mktime()函数创建一个日期的UNIX时间戳:

$timestamp = mktime(0, 0, 0, 8, 5, 2021);

echo "The UNIX timestamp for August 5, 2021 is ".$timestamp;

输出:

The UNIX timestamp for August 5, 2021 is 1628112000

5. strtotime()和date()函数的结合使用

strtotime()和date()函数是两个非常常用的函数,它们经常被用于一起来实现各种日期和时间的操作。

以下是一个简单的示例,演示如何使用strtotime()和date()函数来获取当前日期和时间加上30天:

$current_date = date('Y-m-d');
$future_date = date('Y-m-d', strtotime('+30 days'));

echo "Today's date is ".$current_date;
echo "<br>";
echo "Date after 30 days is ".$future_date;

输出:

Today's date is 2021-08-05
Date after 30 days is 2021-09-04

6. date_diff()函数

date_diff()函数用于计算两个日期之间的差异。

以下是一个简单的示例,演示如何使用date_diff()函数来计算两个日期之间的差异:

$date1 = date_create('2021-08-05');
$date2 = date_create('2021-08-10');
$interval = date_diff($date1, $date2);

echo "The difference between ".$date1->format('Y-m-d')." and ".$date2->format('Y-m-d')." is ".$interval->format('%R%a days');

输出:

The difference between 2021-08-05 and 2021-08-10 is +5 days

7. strftime()函数

strftime()函数可用于格式化日期和时间,与date()函数相似。

以下是一个简单的示例,演示如何使用strftime()函数来格式化当前时间:

$current_time = time();
$formatted_time = strftime('%Y-%m-%d %H:%M:%S', $current_time);

echo "The formatted time is ".$formatted_time;

输出:

The formatted time is 2021-08-16 12:01:23

总结

以上是一些基本的PHP日期和时间函数示例,它们可用于执行各种日期和时间操作。希望这篇文章能够帮助你更好地理解这些功能,并更好地处理日期和时间。