使用PHP日期函数进行日期格式化
发布时间:2023-07-01 08:37:58
PHP日期函数是一组可以用于处理日期和时间的函数。这些函数可以用来格式化日期,计算日期之间的差异,格式化时间等。
以下是一些常用的PHP日期函数及其格式化选项:
1. date(format, timestamp)
该函数返回当前日期和时间的字符串表示。format参数定义了日期的格式,timestamp参数是可选的,用于指定一个特定的日期和时间。
例如:
echo date("Y-m-d"); // 输出当前日期,格式为年-月-日
echo date("H:i:s"); // 输出当前时间,格式为时:分:秒
2. strtotime(time, now)
这个函数将任何英文文本的日期字符串解析为Unix时间戳。
例如:
echo strtotime("now"); // 返回当前时间的Unix时间戳
echo strtotime("10 September 2000"); // 返回 "10 September 2000" 这个日期的Unix时间戳
3. mktime(hour, minute, second, month, day, year)
这个函数返回指定日期和时间的Unix时间戳。
例如:
echo mktime(0, 0, 0, 1, 1, 2022); // 返回2022年1月1日的Unix时间戳
4. strftime(format, timestamp)
这个函数根据指定的格式化选项格式化日期和时间。
例如:
echo strftime("%Y-%m-%d", time()); // 输出当前日期,格式为年-月-日
echo strftime("%H:%M:%S", time()); // 输出当前时间,格式为时:分:秒
5. gmdate(format, timestamp)
这个函数与date()函数类似,但是返回的是格林威治标准时间(GMT)。
例如:
echo gmdate("Y-m-d"); // 输出当前日期,格式为年-月-日
echo gmdate("H:i:s"); // 输出当前时间,格式为时:分:秒
6. date_create(format, timezone)
这个函数用于创建一个新的DateTime对象。
例如:
$date = date_create('2019-02-21', timezone_open('Asia/Tokyo'));
echo date_format($date, 'Y-m-d'); // 输出指定日期,格式为年-月-日
以上是一些常用的PHP日期函数及其格式化选项。通过使用这些函数,您可以轻松地对日期和时间进行格式化和计算。
