Rama Durai
Rama Durai

Reputation: 750

how to find a date from the value of week of the month in laravel..?

I need to find first, second, etc, week in a month.
In that week, i need to find a Monday/Tuesday or else.
I'm using laravel framework and php,

Now, i'm going to find Monday of first week of this September month and
my code is,

    date('Y-m-d', strtotime('+0 week, Monday', strtotime('first day of September 2016')));        

This is correct way or not..?
Here, the answer is no date or 5-9-2016 ..?

Upvotes: 1

Views: 1415

Answers (2)

UP.
UP.

Reputation: 187

I would higly recommend you to read about Carbon, it comes by default with Laravel and is what is used internaly to deal with dates. Also is really handy and easy to use.

Upvotes: 2

Robert Wade
Robert Wade

Reputation: 5003

It's much simpler than you think using strtotime. I believe the last few are what you're after. You'll have to be careful though, some weeks in partiular months may not have a particular day. For instance the 1st week of November 16 does not have a Monday.

<?php

echo date("Y-m-d",strtotime('first monday September 2016')); 
// 2016-09-05 (first Monday of september '16)

echo date("Y-m-d",strtotime('Tuesday +1 week December 2016')); 
// 2016-12-06 (first Tuesday of December '16)

echo date("Y-m-d",strtotime('Friday November 2016')); 
// 2016-11-04 (first Friday of November '16')

echo date("Y-m-d",strtotime('fourth Monday September 2016')); 
// 2016-09-05 (first Monday of september '16)

echo date("Y-m-d",strtotime('Tuesday December 2016')); 
// 2016-12-06 (first Tuesday of December '16)

echo date("Y-m-d",strtotime('third Friday November 2016')); 
// 2016-11-04 (first Friday of November '16')

echo date("Y-m-d",strtotime('Tuesday +1 week December 2016')); 
// 2016-12-06 (Tuesday of the second week of December '16)

echo date("Y-m-d",strtotime('Friday +2 week November 2016')); 
// 2016-11-04 (Friday of the third week of November '16')
?>

Without the '+n week' in the last 2 examples, it's going to return the first matching day in the first week. Adding +1 week makes it the second week it chooses the day from. Adding +2 week makes it the third week it chooses from, etc.

But like I mentioned above, it's not foolproof. For instance:

echo date("Y-m-d",strtotime('Friday +4 week November 2016'))
// 2016-12-02 Although there are 5 calendar weeks in November '16, the 5th   
// week does not have a Friday.  So you're getting December's Friday, because 
// you're simply adding weeks to a day. 

Upvotes: 1

Related Questions