PHP常用日期和时间处理函数汇总
PHP中有许多用于日期和时间处理的常用函数,以下是一些常见的函数和它们的用法:
1. time():返回当前时间的Unix时间戳,即从1970年1月1日开始计算的秒数。
例:$timestamp = time();
2. date(format, timestamp):将时间戳转换为指定格式的日期时间。
例:echo date("Y-m-d H:i:s", $timestamp);
3. strtotime(time_string):将时间字符串转换为Unix时间戳。
例:$timestamp = strtotime("2021-01-01");
4. mktime(hour, minute, second, month, day, year):返回指定日期的Unix时间戳。
例:$timestamp = mktime(0, 0, 0, 1, 1, 2021);
5. strtotime(date_string):将日期字符串转换为Unix时间戳。
例:$timestamp = strtotime("2021-01-01");
6. strtotime('+1 day', $timestamp):对时间戳进行加减计算,返回计算后的时间戳。
例:$next_day = strtotime('+1 day', $timestamp);
7. getdate(timestamp):返回包含日期和时间信息的关联数组。
例:$date_info = getdate($timestamp);
8. strftime(format, timestamp):根据所指定的格式返回日期/时间。
例:echo strftime("%Y-%m-%d %H:%M:%S", $timestamp);
9. date_default_timezone_set(timezone):设置脚本中使用的默认时区。
例:date_default_timezone_set("Asia/Shanghai");
10. strtotime(time_string, base_timestamp):将时间字符串转换为Unix时间戳,可以指定参考时间。
例:$timestamp = strtotime("2021-01-01", $base_timestamp);
11. gmdate(format, timestamp):返回格林威治标准时间(GMT)的日期和时间。
例:echo gmdate("Y-m-d H:i:s", $timestamp);
12. timezones_identifiers(what):返回系统中可用的时区标识符。
例:$timezones = timezone_identifiers_list();
13. date_default_timezone_get():返回当前脚本使用的默认时区标识符。
例:$timezone = date_default_timezone_get();
14. checkdate(month, day, year):检查日期的有效性。
例:$valid = checkdate(12, 31, 2021);
15. date_diff(date1, date2):返回两个日期之间的差异。
例:$date1 = date_create("2021-01-01");
$date2 = date_create("2021-12-31");
$interval = date_diff($date1, $date2);
这些函数提供了强大而灵活的日期和时间处理功能,可以用于各种场景,例如计算日期差异、格式化日期与时间、时区转换等。合理利用这些函数,可以简化开发过程并确保日期和时间的准确性。
