Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding first and last day of the week (or month, quarter, or year) [duplicate]

Tags:

php

mysql

Possible Duplicate:
Grab current first and last day in week in php

I am trying to get the first and last day of the week, month, quarter, and year for a given day.

For instance, for day 2013-01-16, the first and last days would be:

  • Week - It would be 2013-01-13 and 2013-01-19 (assuming Sunday to Saturday)
  • Month - It would be 2013-01-01 and 2013-01-31
  • Quarter - It would be 2013-01-01 and 2013-03-31
  • Year - It would be 2013-01-01 and 2013-12-31

My purpose is to include them in a WHERE myDate BETWEEN 2013-01-13 AND 2013-01-19.

Both a standard MYSQL function solution (but not stored procedure, etc) or PHP solution is acceptable. Thank you


Solution for first and last day of given quarter.

$q=ceil($date->format("n")/3);
$months_start=array('January','April','July','October');
$months_end=array('March','June','September','December');
$m_start=$months_start[$q-1];
$m_end=$months_end[$q-1];
$modifier='first day of '.$m_start.' '.$date->format('Y');
$date->modify($modifier);
echo $modifier.': '.$date->format('Y-m-d').'<br>';
$modifier='last day of '.$m_end.' '.$date->format('Y');
$date->modify($modifier);
echo $modifier.': '.$date->format('Y-m-d').'<br>';
like image 742
user1032531 Avatar asked Feb 17 '23 19:02

user1032531


1 Answers

You can use strtotime:

$date = strtotime('2013-01-16');

// First/last day of week 
$first = strtotime('last Sunday');
$last = strtotime('next Saturday');

Or PHP's native DateTime functionality:

$date = new DateTime('2013-01-16');

// First/last day of month
$first = $date->modify('first day of this month');
$last = $date->modify('last day of this month');

Getting the first/last day of a year might be a little bit more tricky:

// Get date
$date = new DateTime('2013-01-16');

// Format to get date
$year = $date->format('Y');

// Get first day of Jan and last day of Dec
$first = $date->modify("first day of January $year");
$last = $date->modify("last day of December $year");
like image 91
hohner Avatar answered Feb 20 '23 12:02

hohner