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

问题描述:

我有一个格式为yW的字符串。一年之后是周数。我想获得时间戳。我在Windows上使用Php 5.2.17。PHP:将yW格式的字符串解析为时间戳

strtotime()似乎没有可靠的工作。对于字符串'1142'它应该会返回2011年第42周的第一天。

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

给这个一展身手,在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年

+0

这不计算更正,请参阅https://en.wikipedia.org/wiki/ISO_week_date#Calculation ISO周日期计算示例。 – Ciantic 2013-10-15 13:36:55

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'); 
+0

非常优雅,应该更高效:) – Geoffrey 2012-01-11 09:53:48