Maison  >  Article  >  développement back-end  >  Formatage de la date et de l'heure en PHP

Formatage de la date et de l'heure en PHP

WBOY
WBOYoriginal
2023-09-01 20:37:063188parcourir

Formatage de la date et de lheure en PHP

Lors du développement d'un site Web, vous devez souvent travailler avec des dates et des heures. Par exemple, vous souhaiterez peut-être afficher la date à laquelle une publication a été modifiée pour la dernière fois ou mentionner le moment où un lecteur a laissé un commentaire. Vous souhaiterez peut-être également afficher un compte à rebours jusqu'à ce qu'un événement spécial se produise.

Heureusement, PHP est livré avec des fonctions de date et d'heure intégrées qui nous aideront à faire tout cela facilement.

Ce tutoriel vous apprendra comment formater la date et l'heure actuelles en PHP. Vous apprendrez également comment obtenir un horodatage à partir d’une chaîne de date et comment ajouter et soustraire différentes dates.

Obtenir la date et l'heure au format chaîne

La valeur de

date($format, $timestamp) 是 PHP 中最常用的日期和时间函数之一。它将所需的日期输出格式作为第一个参数,并将整数作为时间戳值,需要将其转换为给定的日期格式。第二个参数是可选的,省略它会根据 $format affiche la date et l'heure actuelles au format chaîne.

$format 参数接受一系列字符作为有效值。其中一些字符具有简单的含义:Y 为您提供 4 位年份的完整数字表示形式 (2018),而 y 只为您提供年份的最后两位数字今年 (18)。同样,H 将以 24 小时格式显示小时,并带有前导零,但 h affichera l'heure au format 12 heures avec des zéros non significatifs.

Voici quelques-uns des caractères de format de date les plus courants et leurs valeurs.

Personnages Signification Exemple
D Jour du mois (avec zéro en tête) 03 ou 17
j Jour du mois sans zéro 3 ou 17
D Jour de la semaine représenté par une abréviation de trois lettres Lundi
l Jour de la semaine Lundi
M Le mois est un nombre avec des zéros non significatifs 09 ou 12
n Le mois est un nombre sans zéros non significatifs 9 ou 12
M Mois comme abréviation de trois lettres Septembre
F Tout le mois Septembre
Y Année à deux chiffres 18
Y Toute l'année 2018

Il existe de nombreux autres caractères spéciaux qui peuvent être spécifiés date() 函数的输出。最好查阅 date() Consultez le tableau des caractères de format dans la documentation de la fonction pour plus d'informations sur les cas particuliers.

Regardons maintenant quelques exemples pratiques de la fonction date(). Nous pouvons l'utiliser pour obtenir l'année en cours, le mois en cours, l'heure actuelle, etc. Nous pouvons également l'utiliser pour obtenir la chaîne de date complète.

<?php

// Output — 2018
echo date('Y');

// Output — September 2018
echo date('F Y');

// Output — 13 September, 2018
echo date('d F, Y');

// Output — 13 September, 2018 (Thursday)
echo date('d F, Y (l)');

Vous pouvez également utiliser la fonction date() pour afficher l'heure. Voici quelques-uns des caractères de format d'heure les plus couramment utilisés :

Personnages Signification Exemple
G L'heure au format 12 heures sans zéros non significatifs 1 ou 12
H Heure au format 12 heures avec des zéros non significatifs 01 ou 12
G L'heure au format 24 heures sans zéros non significatifs 1 ou 13
H Heure au format 24 heures avec des zéros non significatifs 01 ou 13
A am/pm minuscule matin
A am/pm en majuscule matin
i Minutes avec des zéros non significatifs 09 ou 15
s Secondes avec des zéros non significatifs 05 ou 30

这里是一些输出格式化时间字符串的示例。

// Output — 11:03:37 AM
echo date('h:i:s A');

// Output — Thursday, 11:04:09 AM
echo date('l, h:i:s A');

// Output — 13 September 2018, 11:05:00 AM
echo date('d F Y, h:i:s A');

?>

如果您想在日期字符串中使用这些特殊字符,转义它们也很重要。

<?php

// Output — CEST201813am18 1115 Thursday.
echo date('Today is l.');

// Output — Today is Thursday.
echo date('\T\o\d\a\y \i\s l.');

// Output — Today is Thursday.
echo 'Today is '.date('l.');

?>

获取 Unix 时间戳

有时,您需要在 PHP 中获取当前 Unix 时间戳的值。借助 time() 函数,这非常容易。它返回一个整数值,描述自 1970 年 1 月 1 日午夜 (00:00:00) GMT 以来经过的毫秒数。

您还可以使用此功能来回返回时间。为此,您所要做的就是从 time() 的当前值中减去正确的秒数,然后将结果值更改为所需的日期字符串。以下是两个示例:

<?php

$ten_days_later = time() + 10*60*60*24;
// Output — It will be Sunday 10 days later.
echo 'It will be '.date('l', $ten_days_later).' 10 days later.';

$ten_days_ago = time() - 10*60*60*24;
// Output — It was Monday 10 days ago.
echo 'It was '.date('l', $ten_days_ago).' 10 days ago.';

?>

您应该记住的一件重要事情是,time() 返回的时间戳值与时区无关,并且获取自 1970 年 1 月 1 日 00:00:00 UTC 以来的秒数。这意味着在特定时间点,此函数将在美国、欧洲、印度或日本返回相同的值。

获取特定日期的时间戳的另一种方法是使用 mktime($hour, $min, $second, $month, $day, $year) 函数。当省略所有参数时,该函数仅使用当前本地日期和时间来计算时间戳值。此函数还可以与 date() 一起使用来生成有用的日期和时间字符串。

<?php

$some_time = mktime(1, 1, 1, 12, 3, 1994);
// Output — It was Saturday on 03 December, 1994.
echo 'It was '.date('l', $some_time).' on '.date('d F, Y', $some_time).'.';

?>

基本上,time() 可用于来回返回一段时间,而 mktime() 在您想要前往某个时间点时很有用特定时间点。

将日期时间字符串转换为时间戳

当您想要将字符串格式的不同日期和时间值转换为时间戳时,strtotime($time, [$now = time()]) 函数将非常有用。该函数可以将几乎所有类型的日期时间字符串解析为时间戳。

您一定要检查有效的时间格式、日期格式、复合日期时间格式和相对日期时间格式。

使用相对日期时间格式,该函数可以轻松地将常用字符串转换为有效的时间戳值。下面的例子应该可以清楚地说明:

<?php

$some_time = strtotime("10 months 15 days 10 hours ago");
// Output — It was Sunday on 29 October, 2017 03:16:46.
echo 'It was '.date('l', $some_time).' on '.date('d F, Y h:i:s', $some_time).'.';

$some_time = strtotime("next month");
// Output — It is Saturday on 13 October, 2018 01:18:05.
echo 'It is '.date('l', $some_time).' on '.date('d F, Y h:i:s', $some_time).'.';

$some_time = strtotime("third monday");
// Output — Date on the third monday from now will be 01 October, 2018.
echo 'Date on the third monday from now will be '.date('d F, Y', $some_time).'.';

$some_time = strtotime("last day of November 2021");
// Output — Last day of November 2021 will be Tuesday.
echo 'Last day of November 2021 will be '.date('l', $some_time).'.';

?>

添加、减去和比较日期

可以在日期中添加或减去特定的时间段。这可以借助 date_add()date_sub() 函数来完成。您还可以使用 date_diff() 函数来减去两个日期并以年、月、日或其他形式输出它们之间的差异。

通常,使用 DateTime 类以面向对象的方式执行任何此类与日期和时间相关的算术比按程序执行更容易。我们将在这里尝试这两种样式,您可以选择您最喜欢的一种。

<?php

$present = date_create('now');
$future = date_create('last day of January 2024');
$interval = date_diff($present, $future);
// Output — 05 years, 04 months and 17 days
echo $interval->format('%Y years, %M months and %d days');

$present = new DateTime('now');
$future = new DateTime('last day of January 2024');
$interval = $present->diff($future);
// Output — 05 years, 04 months and 17 days
echo $interval->format('%Y years, %M months and %d days');

?>

使用 DateTime::diff() 时,会从调用 diff() 方法的 DateTime 对象中减去DateTime 对象,该对象传递给 diff() 方法。当您编写过程样式代码时,将从第二个日期参数中减去第一个日期参数。

该函数和方法都返回一个 DateInterval() 对象,表示两个日期之间的差异。可以使用 format() 方法文档中列出的所有字符来格式化此间隔以提供特定输出。

当减去或增加时间间隔时,面向对象风格和过程风格之间的差异变得更加明显。

您可以使用 DateTime() 构造函数实例化新的 DateTime 对象。同样,您可以使用 DateInterval() 构造函数实例化 DateInterval 对象。它接受一个字符串作为其参数。间隔字符串以 P 开头,表示句点。之后,您可以使用整数值和分配给特定句点的字符来指定每个句点。您应该查看 DateInterval 文档以了解更多详细信息。

下面的示例说明了在 PHP 中添加或减去日期和时间是多么容易。

<?php

$now = new DateTime('now');
$the_interval = new DateInterval('P20Y5M20D');
$now->add($the_interval);

// Output — It will be Saturday, 05 March, 2039 after 20 years, 05 months and 20 days from today.
echo 'It will be '.$now->format('l, d F, Y').' after '.$the_interval->format("%Y years, %M months and %d days").' from today.';

$now = date_create('now');
$the_interval = date_interval_create_from_date_string('20 years 05 months 20 days');
date_add($now, $the_interval);

// Output — It will be Saturday, 05 March, 2039 after 20 years, 05 months and 20 days from today.
echo 'It will be '.$now->format('l, d F, Y').' after '.$the_interval->format("%Y years, %M months and %d days").' from today.';

?>

您还可以使用比较运算符来比较 PHP 中的日期。这有时会派上用场。让我们使用比较运算符和其他 DateTime 方法创建一个圣诞节计数器。

<?php

$now = new DateTime('today');
$christmas = new DateTime('25 December 2018');

while($now > $christmas) {
    $christmas->add(new DateInterval('P1Y'));
}

if($now < $christmas) {
    $interval = $now->diff($christmas);
    echo $interval->format('%a days').' until Christmas!';
}

if($now == $christmas) {
    echo 'Merry Christmas :)';
}

// Output — 103 days until Christmas!

?>

我们首先创建两个 DateTime 对象来存储当前时间和今年圣诞节的日期。之后,我们运行 while 循环,不断向 2018 年圣诞节日期添加 1 年,直到当前日期小于圣诞节日期。当代码在 2024 年 1 月 18 日运行时,这将很有帮助。只要圣诞节日期小于运行此脚本时的当前日期,while 循环就会增加圣诞节日期。

我们的圣诞节计数器现在可以在未来几十年内正常工作,不会出现任何问题。

有关 PHP 中 date() 的常见问题

关于从 PHP 中的 date() 函数获取不同类型的信息,时不时会出现一些常见问题。我们将尽力在这里回答所有问题。

如何获取 PHP 中的当前年份?

您可以使用 date('y')date('Y') 获取 PHP 中的当前年份。使用大写字母 Y 将为您提供当前年份的所有数字,例如 2021。使用小y只会给出最后两位数字,例如21

<?php

echo date('Y');
// 2021

echo date('y');
// 21

?>

在 PHP 中获取当前月份的正确方法是什么?

在 PHP 中,有四种不同的字符用于获取当前月份,具体取决于您想要的格式。您可以使用大写字母 F 获取月份的完整名称,例如 February,或者使用 M 获取较短的三字母格式的月份

您还可以使用mn以数字形式获取当前月份,这将分别为您提供带前导零和不带前导零的月份。

<?php

echo date('F');
// February

echo date('M');
// Feb

echo date('m');
// 02

echo date('n');
//  2

?>

如何用 PHP 获取星期几?

您还可以通过使用四个不同的字符来获取 PHP 中的星期几。大写字母 D 将用三个字母表示一周中的某一天,例如 MonTue。使用 l(小写 L)将为您提供一周中某一天的全名。

您可以使用 w 获取一周中各天的 0(星期日)和 6(星期六)之间的数值>.

<?php

echo date('D');
// Fri

echo date('l');
// Friday

?>

如何在 PHP 中获取 12 小时格式的当前时间?

您可以使用 gh 获取 12 小时格式的当前时间。使用g,您将获得不带任何前导零的时间,而h将添加一些前导零。可以使用a(小写字母)或A(大写字母)添加 AM 或 PM。

<?php

echo date('g:i:s a');
// 5:05:19 am

echo date('h:i:s A');
// 05:05:19 AM

?>

我可以在 PHP 中获取 24 小时格式的当前时间吗?

使用字符GH将为您提供24小时格式的当前小时。 G 不会出现任何前导零,但 H 会添加前导零。

<?php

echo date('G:i:s');
// 15:06:48

?>

转义日期格式字符的最佳方法是什么?

date() 函数接受字符串作为参数,但许多字符都有明确定义的含义,例如 Y 表示年份,F 表示年份月。这意味着直接使用这些字符作为字符串的一部分可能并不总是能获得所需的结果。

如果您希望 date() 函数输出这些字符,那么您必须先对它们进行转义。这是一个例子:

<?php

echo 'Today is '.date("l the jS of F Y");
// Today is Friday 2804Europe/Berlin 19th 2021f February 2021

echo 'Today is '.date("l \\t\h\\e jS \of F Y");
// Today is Friday the 19th of February 2021

?>

某些字符(例如 t)需要两个反斜杠,因为 \t 用于制表符。如果可能,建议将您想要回显的常规字符串放在 date() 之外。否则,您将转义很多字符。

最终想法

在本教程中,我们学习了如何使用 date() 函数以所需格式输出当前日期和时间。我们还看到 date() 也可用于仅获取当前年份、月份等。之后,我们学习了如何获取当前时间戳或将有效的 DateTime 字符串转换为时间戳。最后,我们学习了如何从不同的日期中添加或减去一段时间。

我尝试在此处介绍关键的 DateTime 函数和方法。您绝对应该查看文档以了解本教程中未涵盖的功能。如果您有任何疑问,请随时在评论中告诉我。

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn