1

使用 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

我觉得我错过了一些相当基本的东西。对此的任何帮助将不胜感激,并在此先感谢您!

4

1 回答 1

0

strftime并且strtotime应该帮助你。在你的情况下,这段代码应该做你想做的事:

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

于 2013-01-21T16:57:04.940 回答