转换方法:1、用strtotime()将指定日期转为时间戳,语法“strtotime("日期")”;2、用date()配合格式化字符“N”将时间戳转为表示星期几的数字,语法“date("N",时间戳)”,会返回1(星期一)到7(星期天) 。

本教程操作环境:windows7系统、PHP8.1版、DELL G3电脑

php将指定日期转化为星期的方法

在PHP中,可以使用date()和strtotime()函数来进行转换。

(其实主要用date(),但该函数处理的对象是时间戳;因此我们需要用strtotime()函数先将日期转为时间戳,在交给date()处理。)

1、使用strtotime()函数将指定日期转为时间戳

strtotime() 函数可将英文文本描述的日期时间描述解析为 UNIX 时间戳

<?php
header("Content-type:text/html;charset=utf-8");
$str1="2022-05-1";
$str2="2022-05-11";
$time1=strtotime($str1);
$time2=strtotime($str2);
echo "$str1 的时间戳: ".$time1."<br>";
echo "$str2 的时间戳: ".$time2;
?>

1.png

2、将获取的时间戳转为星期天数

date()可以格式化时间,配合格式化字符“N”获取星期天数

  • N:返回ISO-8601 格式数字表示的星期中的第几天(PHP 5.1.0 新加),范围 1(表示星期一)到 7(表示星期天)

echo "$str1 是星期 ".date("N",$time1)."<br>";
echo "$str2 是星期 ".date("N",$time2);

2.png

查看日历,看看是否正确。

3.png


php怎么将指定日期转化为星期