How to convert week number and year into unix timestamp?

♀尐吖头ヾ 提交于 2019-11-27 06:33:49

问题


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?


回答1:


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 2011 returns January 3 2011.

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

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

Note that the week number needs to be two digits.

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.




回答2:


  • $week: The week number
  • $year: The year number

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.




回答3:


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 any timestamp in the week then that's all you need, else you would have to go to the monday in this week:

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

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



来源:https://stackoverflow.com/questions/5763340/how-to-convert-week-number-and-year-into-unix-timestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!