gpt4 book ai didi

php - 如何找到与模式 7 的 MySQL WEEK 函数等效的 PHP?

转载 作者:行者123 更新时间:2023-11-30 23:23:33 25 4
gpt4 key购买 nike

使用 PHP,我如何在以下位置找到周数:

  • 一周的第一天是星期一,
  • 第 1 周是今年第一个星期一,
  • 范围是 1-53?

我正在尝试实现与 MySQL 代码等效的 PHP:

SELECT WEEK(date('Y-m-d'), 7);

如本网站所示:http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_week

示例(我试图用错误的语言 MySQL 实现的目标):

$dbh = new PDO("mysql:host=localhost;dbname=test", "root", "");

$stmt = $dbh->prepare("SELECT WEEK('2012-12-30', 7) as week");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo "2012-12-30 = ".$result['week']."<br />";

$stmt = $dbh->prepare("SELECT WEEK('2012-12-31', 7) as week");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo "2012-12-31 = ".$result['week']."<br />";

$stmt = $dbh->prepare("SELECT WEEK('2013-01-01', 7) as week");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo "2013-01-01 = ".$result['week']."<br />";

$stmt = $dbh->prepare("SELECT WEEK('2013-01-06', 7) as week");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo "2013-01-06 = ".$result['week']."<br />";

$stmt = $dbh->prepare("SELECT WEEK('2013-01-07', 7) as week");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo "2013-01-07 = ".$result['week']."<br />";

输出:(我正在寻找的输出)

2012-12-30 = 52
2012-12-31 = 53
2013-01-01 = 53
2013-01-06 = 53
2013-01-017 = 1

我的尝试:(使用正确的语言,PHP,但结果错误)

$date = new DateTime('2012-12-30');
echo "2012-12-30 = ".$date->format('W')."<br />";
$date = new DateTime('2012-12-31');
echo "2012-12-31 = ".$date->format('W')."<br />";
$date = new DateTime('2013-01-01');
echo "2013-01-01 = ".$date->format('W')."<br />";
$date = new DateTime('2013-01-06');
echo "2013-01-06 = ".$date->format('W')."<br />";
$date = new DateTime('2013-01-07');
echo "2013-01-07 = ".$date->format('W')."<br />";

输出(错误结果)

2012-12-30 = 52
2012-12-31 = 01
2013-01-01 = 01
2013-01-06 = 01
2013-01-07 = 02

我觉得我缺少一些相当基本的东西。非常感谢您对此提供任何帮助,并在此先感谢您!

最佳答案

strftimestrtotime应该帮助你。在你的情况下,这段代码应该做你想做的:

strftime(%V, strtotime('2013-01-21'))

关于php - 如何找到与模式 7 的 MySQL WEEK 函数等效的 PHP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14443002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com