Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting first / last date of the week

Tags:

Is it possible to get the first / last date of a week using PHP's Relative Date Time format?

I've tried to do:

date_default_timezone_set('Europe/Amsterdam'); $date = new DateTime();  $date->modify('first day of this week'); // to get the current week's first date echo $date->format('Y-m-d'); // outputs 2011-12-19  $date->modify('first day of week 50'); // to get the first date of any week by weeknumber echo $date->format('Y-m-d'); // outputs 2011-12-18  $date->modify('last day of this week'); // to get the current week's last date echo $date->format('Y-m-d'); // outputs 2011-12-17  $date->modify('last day of week 50'); // to get the last date of any week by weeknumber echo $date->format('Y-m-d'); // outputs 2011-12-18 

As you can see it doesn't output the correct dates.

According to the docs this should be possible if I'm correct.

Am I doing something terrible wrong?

EDIT

I need to use PHP's DateTime for dates in the far future.

UPDATE

It gets only stranger now. I've done some more testing.

Windows PHP 5.3.3

2011-12-01  Warning: DateTime::modify() [datetime.modify]: Failed to parse time string (first day of week 50) at position 13 (w): The timezone could not be found in the database in C:\Users\Gerrie\Desktop\ph\Websites\Charts\www.charts.com\public\index.php on line 9 2011-12-01 2011-11-30  Warning: DateTime::modify() [datetime.modify]: Failed to parse time string (last day of week 50) at position 12 (w): The timezone could not be found in the database in C:\Users\Gerrie\Desktop\ph\Websites\Charts\www.charts.com\public\index.php on line 15 2011-11-30 

Linux 5.3.8

2011-12-01 2011-12-01 2011-11-30 2011-11-30 
like image 518
PeeHaa Avatar asked Dec 16 '11 23:12

PeeHaa


1 Answers

I'm a big fan of using the Carbon library, which makes this sort of thing really easy. For example:

use Carbon\Carbon;  $monday = Carbon::now()->startOfWeek() $sunday = Carbon::now()->endOfWeek() 

Or, if you'd prefer to have Sunday be the first day of your week:

use Carbon\Carbon;  Carbon::setWeekStartsAt(Carbon::SUNDAY); Carbon::setWeekEndsAt(Carbon::SATURDAY);  $sunday = Carbon::now()->startOfWeek() $saturday = Carbon::now()->endOfWeek() 
like image 61
Jonathan Avatar answered Nov 16 '22 13:11

Jonathan