Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding First day of week via php [duplicate]

Tags:

date

php

datetime

Possible Duplicate:
Get first day of week in PHP?

Hi,

I want to find first and last date of current week and last week. Similarly I want to find first and last date of current month and last month.

This has to be done in PHP. Please help.

like image 597
Future King Avatar asked Dec 14 '10 13:12

Future King


1 Answers

strtotime is quite powerful with relative time formats:

strtotime('monday this week');
strtotime('sunday this week');
strtotime('monday last week');
strtotime('sunday last week');

(this only works with PHP 5.3+)

strtotime('first day of this month');
strtotime('last day of this month');
strtotime('first day of last month');
strtotime('last day of last month');

In order to get the first and last date of a month in PHP < 5.3, you can use a combination of mktime and date (date('t') gives the number of days of the month):

mktime(0,0,0,null, 1); // gives first day of current month
mktime(0,0,0,null, date('t')); // gives last day of current month

$lastMonth = strtotime('last month');
mktime(0,0,0,date('n', $lastMonth), 1); // gives first day of last month
mktime(0,0,0,date('n', $lastMonth), date('t', $lastMonth); // gives last day of last month

If you just want to get a string for presentation, then you don't need mktime:

date('Y-m-1'); // first day current month
date('Y-m-t'); // last day current month
date('Y-m-1', strtotime('last month')); // first day last month
date('Y-m-t', strtotime('last month')); // last day last month
like image 135
Felix Kling Avatar answered Sep 25 '22 23:09

Felix Kling