卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章71092本站已运行4226

php如何处理日期格式

php 提供多重处理日期格式的方法:使用 date() 函数将 unix 时间戳转换为特定格式的字符串。使用 strtotime() 函数将人类可读的日期字符串转换为 unix 时间戳。使用 date() 函数的字母代码自定义日期格式,如显示年份、月份、日期、小时、分钟和秒。

php如何处理日期格式

PHP 处理日期格式

PHP 提供了多种方法来处理日期格式。最常用的方法是使用 date() 函数和 strtotime() 函数。

date() 函数

date() 函数将 Unix 时间戳转换为指定格式的字符串。其语法如下:

立即学习“PHP免费学习笔记(深入)”;

date(format, timestamp)

其中:

  • format:要转换日期的格式,使用字母代码指定,如 Y(年)、m(月)和 d(日)。
  • timestamp(可选):要转换的 Unix 时间戳。如果未指定,则使用当前时间。

示例:

$timestamp = time();
$date_string = date("Y-m-d H:i:s", $timestamp);
echo $date_string; // 输出:2023-03-08 15:30:00

strtotime() 函数

strtotime() 函数将人类可读的日期字符串转换为 Unix 时间戳。其语法如下:

strtotime(string)

其中:

  • string:要转换的日期字符串,例如 "2023-03-08 15:30:00"。

示例:

$date_string = "2023-03-08 15:30:00";
$timestamp = strtotime($date_string);
echo $timestamp; // 输出:1678293000

自定义日期格式

使用 date() 函数,可以通过使用字母代码来指定自定义日期格式:

  • Y:年份(四位数)
  • y:年份(两位数)
  • m:月份(两位数,01-12)
  • d:日期(两位数,01-31)
  • H:小时(24 小时制,00-23)
  • h:小时(12 小时制,01-12)
  • i:分钟(两位数,00-59)
  • s:秒(两位数,00-59)

示例:

$timestamp = time();
$date_string = date("d/m/Y H:i", $timestamp);
echo $date_string; // 输出:08/03/2023 15:30
卓越飞翔博客
上一篇: php如何支持显示中文
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏