PHP:将格式为yW的字符串解析为时间戳

时间:2012-01-11 08:40:28

标签: php

我有一个格式为yW的字符串。一年后是周数。我想得到一个时间戳。我在Windows上使用Php 5.2.17。

strtotime()似乎无法可靠地运作。对于字符串'1142',它应该返回2011年第42周的第一天。

有关如何执行此操作的任何建议?

2 个答案:

答案 0 :(得分:2)

放手一搏,也可以在Windows上工作......

$date = '1201';
$y = substr($date, 0, 2) + 2000;
$w = substr($date, 2);
$ts = mktime(0, 0, 0, 0, 0, $y) + ($w * 604800);
如果第1周是一年中的第一周,

从周减去1

答案 1 :(得分:2)

strtotime()不接受该特定格式。但是,如果格式为2011W42,则可以使用年份和周数值。

// Convert 1142 to 2011W42
$reformatted = '20'.substr_replace('1142', 'W', 2, 0);
$timestamp   = strtotime($reformatted);

有关此特定格式的详细信息,请参阅Compound Formats

另一个选项是DateTime类上的setIDODate()方法。

sscanf('1142', '%2d%2d', $year, $week);
$date = new DateTime('@0');
$date->setISODate(2000 + $year, $week);
$timestamp = $date->format('U');