php 如何将周数和年份转换为unix时间戳?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5763340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:25:04  来源:igfitidea点击:

How to convert week number and year into unix timestamp?

phpstrtotimestrftimemktime

提问by blacktie24

I'm trying to group together dates into a week number and year, and then I want to convert that week number back into a unix timestamp. How can I go about doing this?

我试图将日期组合成周数和年份,然后我想将该周数转换回 unix 时间戳。我该怎么做呢?

回答by Pekka

I assume you are using ISO 8601 week numbers, and want the first day of a ISO 8601 week so that e.g. Week 1 of 2011returns January 3 2011.

我假设您正在使用 ISO 8601 周数,并且想要 ISO 8601 周的第一天,以便例如Week 1 of 2011返回January 3 2011

strtotimecan do this out of the box using the {YYYY}W{WW}format:

strtotime可以使用以下{YYYY}W{WW}格式开箱即用:

echo date("Y-m-d", strtotime("2011W01")); // 2011-01-03

Note that the week number needs to be twodigits.

需要注意的是周数必须是2个位数。

Shamefully, DateTime::createFromFormat, the fancy new PHP 5 way of dealing with dates, seems unable to parse this kind of information - it doesn't have a "week" placeholder.

可耻的是,DateTime::createFromFormat处理日期的新 PHP 5 奇特方式似乎无法解析此类信息 - 它没有“周”占位符。

回答by Oswald

  • $week: The week number
  • $year: The year number
  • $week: 周数
  • $year: 年号

Then:

然后:

$timestamp = gmmktime (0, 0 , 0 , 1, , 4 + 7*($week - 1), $year);

The 4 + 7*($week - 1)comes from the fact that according to ISO 8601, the first week of the year is the one that contains January 4th.

4 + 7*($week - 1)是因为根据 ISO 8601,一年中的第一周是包含 1 月 4 日的那一周。

回答by Florian

strtotime('1/1/2011 + 4 weeks')(1/1 ist always in week number one; this would bring me to week number five). if you want anytimestamp in the week then that's all you need, else you would have to go to the monday in this week:

strtotime('1/1/2011 + 4 weeks')(1/1 总是在第一周;这将使我进入第五周)。如果您想要本周的任何时间戳,那么这就是您所需要的,否则您将不得不去本周的星期一:

$t = strtotime('1/1/2011 + 4 weeks');
$t -=  24 * 60 * 60 * date('w', $t);

Update: Instead of 1/1/2011use the first monday in 2011. The 2nd calculation is not needed anymore.

更新:而不是1/1/2011使用 2011 年的第一个星期一。不再需要第二次计算。