Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert week number and year into unix timestamp?

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?

like image 283
blacktie24 Avatar asked Apr 23 '11 09:04

blacktie24


People also ask

What is Unix timestamp format?

Unix time is a way of representing a timestamp by representing the time as the number of seconds since January 1st, 1970 at 00:00:00 UTC. One of the primary benefits of using Unix time is that it can be represented as an integer making it easier to parse and use across different systems.

How do I get the day of the week from a Unix timestamp?

In summary: day of week = (floor(T / 86400) + 4) mod 7. (This assumes that you want the day of week in UTC. If you want to calculate it for another time zone, you need to perform some addition or subtraction of hours and minutes on T first.)

How do you convert date to epoch time?

Convert from human-readable date to epochlong epoch = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("01/01/1970 01:00:00").getTime() / 1000; Timestamp in seconds, remove '/1000' for milliseconds. date +%s -d"Jan 1, 1980 00:00:01" Replace '-d' with '-ud' to input in GMT/UTC time.


2 Answers

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.

like image 74
Pekka Avatar answered Oct 04 '22 17:10

Pekka


  • $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.

like image 40
Oswald Avatar answered Oct 04 '22 19:10

Oswald