Tutorial
Introduction
By using these functions you will be able to get a date of any day of a week in a year. This could be very useful sometimes... I had to use it myself not long ago for a newspaper system and it took me weeks to find out how to do it!
Hopefully it's going to help some of you guys out there.
Step 1 - The first function
We're going to need a function which will get us some raw information.
Code:
<?php
function getDaysInWeek ($weekNumber, $year) {
// Count from '0104' because January 4th is always in week 1
// (according to ISO 8601).
$time = strtotime($year . '0104 +' . ($weekNumber - 2). ' weeks');
// Get the time of the first day of the week
$mondayTime = strtotime('-' . (date('w', $time) - 1) . ' days',$time);
// Get the times of days 0 -> 6
$dayTimes = array ();
for ($i = 0; $i < 7; ++$i) {
$dayTimes[] = strtotime('+' . $i . ' days', $mondayTime);
}
// Return timestamps for mon-sun.
return $dayTimes;
}
?>
Now we have created a function which will return an array with timestamps for each day of that week.
Step 2 - Second function
To get the date of the week you want we are going to create a function too, I will use an example to get friday's date because that's the one I had to use... but there will be endless possibilities with this function when you start tweaking it.
Code:
<?php
function get_friday($week,$jaar){
// A week = mo - su
// We will now use the function from step 1 to get the timestamps
$dayTimes = getDaysInWeek($week, $jaar);
// Loop through our array and display formatted week day info:
$i=0; // $i will represent the weekday, 0-6, mo-su
foreach ($dayTimes as $dayTime) {
if($i == 4){return (strftime('%d-%m-%Y', $dayTime));}
$i++;
}
}
?>
That should make sense to you all, you can change the function so it will display any day of the week... or mayb you would like to specify what day of the week you want in the function, endless options as I said before hehe.
Good luck!
A tip in case you would like to use timestamps afterwards!
The date generated with the strftime will need a little work-around if you would like to change it into a timestamp:
Code:
<?php
$friday = strptime(get_friday(date('W'),date('Y')),'%d-%m-%Y');
$timestamp = mktime($friday['tm_hour'],$friday['tm_min'],$friday['tm_sec'],($friday['tm_mon']+1),$friday['tm_mday'],($friday['tm_year']+1900));
?>
Very stupid... but oh well ;)
| « Previous |
Comments
You have to be logged in to write a comment.



