0

I have three pieces of information extracted from my database, the year, the number of week (1-52), and the day of week (mon, tue, wed). And I need to convert it in to a date.

How would I go about doing that in php?

user2688737
  • 41
  • 1
  • 2
  • 6
  • And what have you tried so far ? – Rikesh Feb 10 '14 at 12:44
  • Very close to duplicate: http://stackoverflow.com/questions/5763340/how-to-convert-week-number-and-year-into-unix-timestamp PHP `strtotime()` will do it for you – jtheman Feb 10 '14 at 12:44

3 Answers3

1

Try this :

$yr="2014";
$week="01";
$day = "Mon";
echo date("Y-m-d", strtotime($yr."W".$week."D ".$day));

PHP fiddle:http://phpfiddle.org/main/code/nzg-ws6

Suresh Kamrushi
  • 15,627
  • 13
  • 75
  • 90
  • 1
    I tried this: $yr="2014"; $week="01"; $day ='mon'; echo date("Y-m-d", strtotime($yr."W".$week."D ". $day)); and it resulted: 2014-01-03 It's wrong. Because, 2014-01-3 it's Friday! – user2688737 Feb 10 '14 at 12:57
1

Did a little digging and it looks like the day will need to be in numerical format for the strtotime conversion to work properly. Using a string such as 'Monday' won't work.

$yr = "2014";
$week = "01";
$day = "1"; //Monday
echo date("Y-m-d", strtotime($yr . "W" . $week . $day)); // "2014W011"

Note that I didn't include the 'D' prefix for the day as this looks to be following ISO8601.

Swapping your days to numbers can be done a few ways: You could make an array Monday to Sunday and use the array key, or maybe a little easier you could do something like this:

$day date("N", strtotime("Monday")); // will echo 1

So the full code could look something like this:

$yr = "2014";
$week = "01";
$day = date("N", strtotime("Monday")); //
echo date("Y-m-d", strtotime($yr . "W" . $week . $day)); // "2014W011"

Here is a demo to check: http://3v4l.org/EllgQ

stckrboy
  • 379
  • 10
  • 16
0

This converts you $day value to desired day format. try this

$yr="2011";
$week="01";
$day="Monday";
$day=date("D",strtotime($day));
echo date("Y-m-d", strtotime($yr."W".$week."D ".$day));;

Demo

krishna
  • 4,069
  • 2
  • 29
  • 56