How can we split dates in php? - php

How can we split dates using PHP? Is there any built in function in PHP?
2016-11-01 10:00:00 till 2016-11-03 18:00:00
I need to split above date in to required dates:-
2016-11-01 10:00:00 till 23:59:59
2016-11-02 00:00:00 till 23:59:59
2016-11-03 00:00:00 till 18:00:00

To my knowledge PHP does not provide such built-in feature.
But you can easily achieve this with th DateTime object :
$interval = '2016-11-01 10:00:00 till 2016-11-03 18:00:00';
$dates = explode(' till ', $interval);
if(count($dates) == 2) {
$current = $begin = new DateTime($dates[0]);
$end = new DateTime($dates[1]);
$intervals = [];
// While more than 1 day remains
while($current->diff($end)->format('%a') >= 1) {
$nextDay = clone $current;
$nextDay->setTime(23,59,59);
$intervals []= [
'begin' => $current->format('Y-m-d H:i:s'),
'end' => $nextDay->format('Y-m-d H:i:s'),
];
$current = clone $nextDay;
$current->setTime(0,0,0);
$current->modify('+1 day');
}
// Last interval : from $current to $end
$intervals []= [
'begin' => $current->format('Y-m-d H:i:s'),
'end' => $end->format('Y-m-d H:i:s'),
];
print_r($intervals);
}

You can use for loop to achieve such type of result. Your requirement is to print date in one day difference between start and end date. I have write code for this .
<?php
$startDate = strtotime('2016-11-01 10:00:00');
$endDate = strtotime('2016-11-03 18:00:00');
for ($loopStart = $startDate; $loopStart <= $endDate; $loopStart = strtotime('+1 day', $loopStart)) {
// check last date
if($endDate >= strtotime('+1 day', $loopStart)){
echo date('Y-m-d', $loopStart).' 23:59:59';
}
else{
echo date('Y-m-d', $loopStart).' '.date('H:i:s',$endDate);
}
echo "<br>";
}
?>
The output of the code is -
2016-11-01 23:59:59
2016-11-02 23:59:59
2016-11-03 18:00:00

Related

Carbon custom start and end of the week by timestamp

I have a list of records with $clocked_in timestamps. I want to display its week start and end date, so I came up with this:
$timesheetWeekStartDate = Carbon::parse($clocked_in)->startOfWeek()->setTimezone($timezone)->addHours(12)->addMinute()->format('Y-m-d H:i');
$timesheetWeekEndDate = Carbon::parse($clocked_in)->endOfWeek()->setTimezone($timezone)->addHours(12)->addMinute()->format('Y-m-d H:i');
$timesheet->period = $timesheetsWeekStartDate . ' - ' . $timesheetWeekEndDate;
It seems to be working, but I would like to have customized start and end of week - add 12 hours ahead. So next week would start/end on 2022-05-23 12:01 - 2022-05-29 12:00, not 2022-05-23 23:59 - 2022-05-29 00:00.
For example, if $clocked_in is starts on Monday 05:00 I want it to display the previous week, not current(because its not 12:01 yet).
How I can achieve that by utilising Carbon?
Didn't find a solution in Carbon, so made it in plain DateTime, here is solution:
$timesheet->clocked_in = '2022-05-21 21:20:04';
$start = date('Y-m-d', strtotime('-2 week', strtotime($timesheet->clocked_in)));
$end = date('Y-m-d', strtotime('+2 week', strtotime($timesheet->clocked_in)));
$period = new DatePeriod(
new DateTime($start),
new DateInterval('P1W'),
new DateTime($end)
);
$periods = [];
foreach ($period as $periodDate) {
$start = $periodDate;
$end = clone $periodDate;
$periods[] = [
'start' => $start->setTimezone(new DateTimeZone($user->account->timezone))->add(new DateInterval('PT12H'))->add(new DateInterval('PT1M'))->format('Y-m-d H:i'),
'end' => $end->setTimezone(new DateTimeZone($user->account->timezone))->add(new DateInterval('P7D'))->add(new DateInterval('PT12H'))->format('Y-m-d H:i'),
];
}
foreach ($periods as $period) {
if (($timesheet->clocked_in >= $period['start']) && ($timesheet->clocked_in <= $period['end'])) {
$timesheets[$timesheetKey]->period = date('m/d/Y', strtotime($period['start'])) . ' - ' . date('m/d/Y', strtotime($period['end']));
}
}

Finding last 7 working days in PHP

I am trying to find out last 7 working days (excluding Saturday and Sunday) from the current day. I am able to get last 7 days of the week, but unable to get the 7 working day's.
//code to found last 7 days
$date = '04/30/2009'; // set current date
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date);
// calculate the number of days since Monday
$dow = date('w', $ts);
$offset = $dow - 1;
if ($offset < 0) {
$offset = 6;
}
// calculate timestamp for the Monday
$ts = $ts - $offset*86400;
// loop from Monday till Sunday
for ($i = 0; $i < 7; $i++, $ts += 86400){
print date("m/d/Y l", $ts) . "\n". "<br>";
}
But I wanted to find last 7 working days. Thanks in advance!
It's relatively easy to work backwards from a point int time to find the "working days" but finding "holidays" is far more complicated and would require considerably more code than this I suspect.
Using the DateTime class you can use the sub method to subtract whatever interval value you wish, in this case P1D is one day.
$strdate='04/30/2009';
$days=11;
$timezone=new DateTimeZone('Europe/London');
$interval=new DateInterval('P1D');
$start=new DateTime( date( DATE_COOKIE, strtotime( $strdate ) ), $timezone );
$end=new DateTime( date( DATE_COOKIE, strtotime( $start->format( DATE_COOKIE ) . '-' . $days .' days' ) ), $timezone );
$dates=array();
while( $start->sub( $interval ) > $end ){
/* is the day integer less than 6(sat)? */
if( $start->format('N') < 6 && count( $dates ) < 7 ) $dates[]=$start->format( DATE_COOKIE );
}
echo '<pre>',print_r( $dates,true ),'</pre>';
This outputs:
Array
(
[0] => Wednesday, 29-Apr-09 00:00:00 BST
[1] => Tuesday, 28-Apr-09 00:00:00 BST
[2] => Monday, 27-Apr-09 00:00:00 BST
[3] => Friday, 24-Apr-09 00:00:00 BST
[4] => Thursday, 23-Apr-09 00:00:00 BST
[5] => Wednesday, 22-Apr-09 00:00:00 BST
[6] => Tuesday, 21-Apr-09 00:00:00 BST
)
I did a little playing around with a public api for getting public holiday information and cobbled the following together...I don't know what sort of coverage this api has for different countries but might be worth investigation.
Different country and region codes can be found here
$api='http://kayaposoft.com/enrico/json/v1.0/';
$params=array(
'action' => 'getPublicHolidaysForDateRange',
'fromDate' => '',
'toDate' => '',
'country' => 'eng' #England
);
$strdate='2017/12/30';
$days=7;
$timezone=new DateTimeZone('Europe/London');
$interval=new DateInterval('P1D');
$start=new DateTime( date( 'Y-m-d', strtotime( $strdate ) ), $timezone );
$end=new DateTime( date( 'Y-m-d', strtotime( $start->format( 'Y-m-d' ) . '-' . $days .' days' ) ), $timezone );
$params['fromDate']=$end->format('d-m-Y');
$params['toDate']=$start->format('d-m-Y');
$query=http_build_query( $params );
$url=$api.'?'.$query;
$json=json_decode( file_get_contents( $url ) );
if( json_last_error() !== 0 ){
$json=false;
}
function isholiday( $obj=false, $y=0, $m=0, $d=0 ){
if( $obj && !empty( $obj ) ){
foreach( $obj as $item ){
$date=$item->date;
if( $date->day==$d && $date->month=$m && $date->year==$y ) return $item->localName;
}
}
return false;
}
$dates=array();
while( $start->sub( $interval ) > $end ){
if( $start->format('N') < 6 && count( $dates ) < $days ) {
$holiday=isholiday( $json, $start->format('Y'), $start->format('m'), $start->format('d') );
$date=$start->format( 'Y-m-d' );
$dates[]=$holiday ? $date .' - '.$holiday : $date;
}
}
echo '<pre>',print_r( $dates, true ),'</pre>';
This outputs the following:
Array
(
[0] => 2017-12-29
[1] => 2017-12-28
[2] => 2017-12-27
[3] => 2017-12-26 - Boxing Day
[4] => 2017-12-25 - Christmas Day
)
Finding holidays will be more complicated.
One solution can be like saving the holidays in advance and skip them if they comes in the condition.
One simple solution for your problem can be like this.
<?php
$holiday = array(
'2017-12-16' => 'Victory Day of Bangladesh',
'2017-12-25' => 'Christmas'
);
$i = 0;
$work_day = '2017-12-26';
while($i != 7)
{
$work_day = date('Y-m-d', strtotime('-1 day', strtotime($work_day)));
$day_name = date('l', strtotime($work_day));
if($day_name != 'Saturday' && $day_name != 'Sunday' && !isset($holiday[$work_day]))
{
echo $work_day."\n";
$i++;
}
}
?>
If you need 7 days without weekend days you need to check the numeric representation of the day of the week, ie "N" Format of date('N').
When skipping 2 weekend days you need increase the for loop to 9 days:
//code to found last 7 days
$date = '04/30/2009'; // set current date
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date);
// calculate the number of days since Monday
$dow = date('w', $ts);
$offset = $dow - 1;
if ($offset < 0) {
$offset = 6;
}
// calculate timestamp for the Monday
$ts = $ts - $offset*86400;
// loop from Monday till Sunday
for ($i = 0; $i < 9; $i++, $ts += 86400){
if(date("N", $ts) < 6){ // day code is less then weekday 6 & 7
print date("m/d/Y l", $ts) . "\n". "<br>";
}
}
https://eval.in/916514
Simple code with possibility to add holidays:
<?php
$date = new DateTime('03/02/2009');
$interval = new DateInterval('P1D');
function isWorkingDay($date)
{
$weekDay = $date->format('w');
if ($weekDay == 0) // sunday
return false;
if ($weekDay == 6) // saturday
return false;
if ($date->format('m-d') == '07-05') // your check, example 5th July
return false;
return true;
}
$workingDays = [];
while(count($workingDays) != 7) {
if(isWorkingDay($date)) {
$workingDays[] = clone $date;
}
$date->sub($interval);
}
foreach($workingDays as $workingDay) {
echo $workingDay->format('Y-m-d') . ', ';
}
Result - list of days without weekend days:
2009-03-02, 2009-02-27, 2009-02-26, 2009-02-25, 2009-02-24, 2009-02-23, 2009-02-20,

How to divide datetime period into separate days in PHP

I need to divide time period for example from:
2015-11-22 11:22:33 to 2015-11-24 02:02:04
into something like this:
2015-11-22 11:22:33 - 2015-11-22 23:59:59
2015-11-23 00:00:00 - 2015-11-23 23:59:59
2015-11-24 00:00:00 - 2015-11-24 02:02:04.
It has to work also for periods shorter than 24h, so for
2015-11-22 11:22:33 to 2015-11-23 02:02:04
I need this:
2015-11-22 11:22:33 - 2015-11-22 23:59:59
2015-11-23 00:00:00 - 2015-11-23 02:02:04.
I found almost perfect piece of code, but it only works for periods longer than 24h and I don't know how to tune it.
<?php
$start_date = '27:04:2013';
$start_time = '16:30';
$end_date = '29:04:2013';
$end_time = '22:30';
// Date input strings and generate a suitable DatePeriod
$start = DateTime::createFromFormat("d:m:Y H:i", "$start_date $start_time");
$end = DateTime::createFromFormat("d:m:Y H:i", "$end_date $end_time");
$interval = new DateInterval('P1D');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $date) {
// Get midnight at start of current day
$date_start = clone $date;
$date_start->modify('midnight');
// Get 23:59:59, end of current day
// (moving to midnight of next day might be good too)
$date_end = clone $date;
$date_end->modify('23:59:59');
// Take care of partial days
$date_start = max($start, $date_start);
$date_end = min($end, $date_end);
// Here you would construct your array of
// DateTime pairs, or DateIntervals, as you want.
printf(
"%s -> %s \n",
$date_start->format('Y-m-d H:i'),
$date_end->format('Y-m-d H:i')
);
}
?>
Try this:
$date1 = '2015-11-22 11:22:33';
$date2 = '2015-11-23 12:22:34';
$f1 = strtotime($date1);
$f2 = strtotime(substr($date1, 0, 10) . " 23:59:59");
while($f2 < strtotime($date2)) {
print(date('Y-m-d H:i:s',$f1) .' - ' .date('Y-m-d H:i:s',$f2).'<br>');
$f1 = strtotime(date('Y-m-d H:i:s', $f2) .' +1 second');
$f2 = strtotime(date('Y-m-d H:i:s', $f2) .' +1 day');
}
print(date('Y-m-d H:i:s',$f1) .' - ' .$date2.'<br>');
See here: http://sandbox.onlinephpfunctions.com/code/77eaae15fdd7c0d2ca1f02a2d225c17199218819
$datetime1 = new DateTime('2015-11-22 11:22:33');
$datetime2 = new DateTime('2015-11-23 02:02:04');
$interval = $datetime1->diff($datetime2);
var_dump($interval->format('%y-%m-%d %h:%i:%s'));
// RESULT: string(14) "0-0-0 14:39:31"
References:
http://php.net/manual/de/datetime.diff.php
http://php.net/manual/de/class.dateinterval.php
http://php.net/manual/de/dateinterval.format.php

Year and week to date in php

I have two pieces of information extracted from a MySQL database, the year(2009, 2010, ect) and the week (1-52). And I need to convert it in to a date start and date end..
For example:
Year=2010, Week=1 would be (Friday, Jan 1st, 2010) - (Sunday, Jan 3rd, 2010)
Year=2010, Week=33 would be (Monday, Aug 16th, 2010) - (Sunday, Aug 22nd, 2010)
Year=2010, Week=34 would be (Monday, Aug 23rd, 2010) - (Sunday, Aug 29th, 2010)
How would I go about doing that in php ?
$year = "2010"; // Year 2010
$week = "01"; // Week 1
$date1 = date( "l, M jS, Y", strtotime($year."W".$week."1") ); // First day of week
$date2 = date( "l, M jS, Y", strtotime($year."W".$week."7") ); // Last day of week
echo $date1 . " - " . $date2;
If week number is under 10 then append a 0 before number. 1 won't work, it should be 01.
Since this question and the accepted answer were posted the DateTime classes make this much simpler to do:-
function daysInWeek($weekNum)
{
$result = array();
$datetime = new DateTime();
$datetime->setISODate((int)$datetime->format('o'), $weekNum, 1);
$interval = new DateInterval('P1D');
$week = new DatePeriod($datetime, $interval, 6);
foreach($week as $day){
$result[] = $day->format('d/m/Y');
}
return $result;
}
var_dump(daysInWeek(24));
Output:-
array (size=7)
0 => string '10/06/2013' (length=10)
1 => string '11/06/2013' (length=10)
2 => string '12/06/2013' (length=10)
3 => string '13/06/2013' (length=10)
4 => string '14/06/2013' (length=10)
5 => string '15/06/2013' (length=10)
6 => string '16/06/2013' (length=10)
This has the added advantage of taking care of leap years etc..
function getStartAndEndDate($week, $year)
{
//setting the default time zone
date_default_timezone_set('America/New_York');
//getting the
//$firstWeek = date('W',strtotime("January 1 $year", date(time())));
//echo "Year : ".$year."<br/>"."Week : ".$week."<br/>";
$firstWeekThursDay = date('W',strtotime("January $year first thursday",date(time())));
if($firstWeekThursDay == "01")
{
$time = strtotime("January $year first thursday",date(time()));
//echo $time."<br/>";
//echo date('Y-m-d H:i:s',$time)."<br/>";
$time = ($time-(4*24*3600))+(((7*$week)-6)*24*3600);
//echo $time."<br/>";
//echo date('Y-m-d H:i:s',$time)."<br/>";
$return[0] = date('Y-m-d', $time);
$time += 6*24*3600;
$return[1] = date('Y-m-d', $time);
//print_r($return);
}
else
{
$time = strtotime("January 1 $year", time());
//echo "<br/>".$time."<br/>";
//echo date('Y-m-d H:i:s',$time)."<br/>";
$time = ($time-(4*24*3600))+(((7*$week)-6)*24*3600);
//echo $time."<br/>";
//echo date('Y-m-d H:i:s',$time)."<br/>";
$return[0] = date('Y-m-d', $time);
$time += 6*24*3600;
$return[1] = date('Y-m-d', $time);
//print_r($return);
//echo "<br/>End of Hi<br/>";
}
return $return;
}
Try this out:
$year = 2000;
$week = 1;
$start = date("l, M jS, Y", strtotime("01 Jan ".$year." 00:00:00 GMT + ".$week." weeks"));
$end = date("l, M jS, Y", strtotime($start." + 1 week"));
echo $start." to ".$end;
You need to set $year and $week. It will then print the interval as specified.
For instance, the output as-is is:
Friday, Jan 7th, 2000 to Friday, Jan 14th, 2000
Note that weeks are indexed from 0-51 (easy to fix).
It's kind of ugly, but it works. Hope that helps!

Get Start and End Days for a Given Week in PHP

I'm trying to get the week range using Sunday as the start date, and a reference date, say $date, but I just can't seem to figure it out.
For example, if I had $date as 2009-05-01, I would get 2009-04-26 and 2009-05-02. 2009-05-10 would yield 2009-05-10 and 2009-05-16. My current code looks like this (I can't remember where I lifted it from, as I forgot to put down the url in my comments):
function x_week_range(&$start_date, &$end_date, $date)
{
$start_date = '';
$end_date = '';
$week = date('W', strtotime($date));
$week = $week;
$start_date = $date;
$i = 0;
while(date('W', strtotime("-$i day")) >= $week) {
$start_date = date('Y-m-d', strtotime("-$i day"));
$i++;
}
list($yr, $mo, $da) = explode('-', $start_date);
$end_date = date('Y-m-d', mktime(0, 0, 0, $mo, $da + 6, $yr));
}
I realized all it did was add 7 days to the current date. How would you do this?
I would take advantange of PHP's strtotime awesomeness:
function x_week_range(&$start_date, &$end_date, $date) {
$ts = strtotime($date);
$start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
$start_date = date('Y-m-d', $start);
$end_date = date('Y-m-d', strtotime('next saturday', $start));
}
Tested on the data you provided and it works. I don't particularly like the whole reference thing you have going on, though. If this was my function, I'd have it be like this:
function x_week_range($date) {
$ts = strtotime($date);
$start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
return array(date('Y-m-d', $start),
date('Y-m-d', strtotime('next saturday', $start)));
}
And call it like this:
list($start_date, $end_date) = x_week_range('2009-05-10');
I'm not a big fan of doing math for things like this. Dates are tricky and I prefer to have PHP figure it out.
To everyone still using mktime(), strtotime() and other PHP functions... give the PHP5 DateTime Class a try. I was hesitant at first, but it's really easy to use. Don't forget about using clone() to copy your objects.
Edit: This code was recently edited to handle the case where the current day is Sunday. In that case, we have to get the past Saturday and then add one day to get Sunday.
$dt_min = new DateTime("last saturday"); // Edit
$dt_min->modify('+1 day'); // Edit
$dt_max = clone($dt_min);
$dt_max->modify('+6 days');
Then format as you need it.
echo 'This Week ('.$dt_min->format('m/d/Y').'-'.$dt_max->format('m/d/Y').')';
Make sure to set your timezone early in your code.
date_default_timezone_set('America/New_York');
Apparently 'w' formatting value of date() or the format method of a DateTime object will return the day of the week as a number (by default, 0=Sunday, 1=Monday, etc)
You could take this and subtract it's value as days from the current day to find the beginning of the week.
$start_date = new DateTime("2009-05-13");
$day_of_week = $start_date->format("w");
$start_date->modify("-$day_of_week day");
$start_date will now be equal to the Sunday of that week, from there you can add 7 days to get the end of the week or what-have-you.
Base on #jjwdesign's answer, I developed a function that can calculate the beginning and ending of a week for a specific date using the DateTime class. WILL WORK ON PHP 5.3.0++
The difference is you can set the day you want as the "beginning" between 0 (monday) and 6 (sunday).
Here's the function :
if(function_exists('grk_Week_Range') === FALSE){
function grk_Week_Range($DateString, $FirstDay=6){
# Valeur par défaut si vide
if(empty($DateString) === TRUE){
$DateString = date('Y-m-d');
}
# On va aller chercher le premier jour de la semaine qu'on veut
$Days = array(
0 => 'monday',
1 => 'tuesday',
2 => 'wednesday',
3 => 'thursday',
4 => 'friday',
5 => 'saturday',
6 => 'sunday'
);
# On va définir pour de bon le premier jour de la semaine
$DT_Min = new DateTime('last '.(isset($Days[$FirstDay]) === TRUE ? $Days[$FirstDay] : $Days[6]).' '.$DateString);
$DT_Max = clone($DT_Min);
# On renvoie les données
return array(
$DT_Min->format('Y-m-d'),
$DT_Max->modify('+6 days')->format('Y-m-d')
);
}
}
Results :
print_r(grk_Week_Range('2013-08-11 16:45:32', 0));
print_r(grk_Week_Range('2013-08-11 16:45:32', 1));
print_r(grk_Week_Range('2013-08-11 16:45:32', 2));
print_r(grk_Week_Range('2013-08-11 16:45:32', 3));
print_r(grk_Week_Range('2013-08-11 16:45:32', 4));
print_r(grk_Week_Range('2013-08-11 16:45:32', 5));
print_r(grk_Week_Range('2013-08-11 16:45:32', 6));
Array
(
[0] => 2013-07-29
[1] => 2013-08-04
)
Array
(
[0] => 2013-07-30
[1] => 2013-08-05
)
Array
(
[0] => 2013-07-31
[1] => 2013-08-06
)
Array
(
[0] => 2013-07-25
[1] => 2013-07-31
)
Array
(
[0] => 2013-07-26
[1] => 2013-08-01
)
Array
(
[0] => 2013-07-27
[1] => 2013-08-02
)
Array
(
[0] => 2013-07-28
[1] => 2013-08-03
)
I have decided to go with the approach at http://boonedocks.net/mike/archives/114-Figuring-the-Start-of-the-Week-with-PHP.html instead.
Here's my version, which uses a similar notion to Clay's:
/**
* Start of the week
*
* 0 = Sun, 1 = Mon, etc.
*/
define( 'WEEK_START', 0 );
/**
* Determine the start and end dates for
* the week in which the specified date
* falls
*
* #param $date Date in week
* #param $start Week start (out)
* #param $end Week end (out)
*/
function week_bounds( $date, &$start, &$end ) {
$date = strtotime( $date );
// Find the start of the week, working backwards
$start = $date;
while( date( 'w', $start ) > WEEK_START ) {
$start -= 86400; // One day
}
// End of the week is simply 6 days from the start
$end = date( 'Y-m-d', $start + ( 6 * 86400 ) );
$start = date( 'Y-m-d', $start );
}
Lightly tested. Code may not be bulletproof, or handle dates in the far past or future. Use at your own risk. Do not immerse the code in water. Do not show the code to those of a nervous disposition, or with a hatred of the dollar sign. Not tested on animals. Safe for use by vegetarians. Author warrants that the code will never, ever speak to you. In the unlikely event that the code does try to engage you in conversation, the author advises you to disregard any and all advice it gives.
Use this to get the "week" number from any given date.
//October 29, 2009 is my birthday
echo $week date('W', strtotime('2009-10-29'));
//OUTPUT: 44
//October 29 is the 44th week in the year 2009
Now pass the parameters for getWeekDates function as "year (2009)" and "$week".
function getWeekDates($year, $week, $start=true){
$from = date("Y-m-d", strtotime("{$year}-W{$week}-1")); //Returns the date of monday in week
$to = date("Y-m-d", strtotime("{$year}-W{$week}-7")); //Returns the date of sunday in week
if($start) {
return $from;
} else {
return $to;
}
//return "Week {$week} in {$year} is from {$from} to {$to}.";
}
For More Info Please refer this link
http://blog.ekini.net/2009/07/09/php-get-start-and-end-dates-of-a-week-from-datew/
In trying to find a more streamlined version of the accepted answer by Paolo Bergantino, I discovered a really nice way to get this done:
function x_week_range2($date) {
$ts = strtotime($date);
$start = strtotime('sunday this week -1 week', $ts);
$end = strtotime('sunday this week', $ts);
return array(date('Y-m-d', $start), date('Y-m-d', $end));
}
The 'sunday this week' string always means "The Sunday at the end of this week." If used on a timestamp that falls on a Sunday, it will be the following Sunday. This lets you avoid the need for the ternary operator in Paola's solution.
You can now use DateTime to get start/end dates of week(s)
function getDateRangeForAllWeeks($start, $end){
$fweek = getDateRangeForWeek($start);
$lweek = getDateRangeForWeek($end);
$week_dates = [];
while($fweek['sunday']!=$lweek['sunday']){
$week_dates [] = $fweek;
$date = new DateTime($fweek['sunday']);
$date->modify('next day');
$fweek = getDateRangeForWeek($date->format("Y-m-d"));
}
$week_dates [] = $lweek;
return $week_dates;
}
function getDateRangeForWeek($date){
$dateTime = new DateTime($date);
$monday = clone $dateTime->modify(('Sunday' == $dateTime->format('l')) ? 'Monday last week' : 'Monday this week');
$sunday = clone $dateTime->modify('Sunday this week');
return ['monday'=>$monday->format("Y-m-d"), 'sunday'=>$sunday->format("Y-m-d")];
}
Usage
print_r( getDateRangeForWeek("2016-05-07") );
print_r( getDateRangeForAllWeeks("2015-11-07", "2016-02-15") );
To be honest, I have trouble understanding the code you posted ;)
I guess something like this should do the trick:
function get_week($date) {
$start = strtotime($date) - strftime('%w', $date) * 24 * 60 * 60;
$end = $start + 6 * 24 * 60 * 60;
return array('start' => strftime('%Y-%m-%d', $start),
'end' => strftime('%Y-%m-%d', $end));
}
Without doing so much string manipulation, you can do some simple math on the timestamps.
function getDateRange(&$start, &$end, $date) {
$seconds_in_day = 86400;
$day_of_week = date("w", $date);
$start = $date - ($day_of_week * $seconds_in_day);
$end = $date + ((6 - $day_of_week) * $seconds_in_day);
}
Based on David Bélanger's version (unfortunatelly, my rep. won't allow me to post comment as reaction to his post..).
When input date is monday and first day of week is set as monday, original version returns previous week, not current.
Here's the little fix (with the rest of orig. function):
if(function_exists('grk_Week_Range') === FALSE){
function grk_Week_Range($DateString, $FirstDay=6){
if(empty($DateString) === TRUE){
$DateString = date('Y-m-d');
}
# fix
$dayOfWeek = date('N', strtotime($DateString));
if ($dayOfWeek == ($FirstDay +1)) { $whichWeek = 'this '; }
else { $whichWeek = 'last '; }
$Days = array(
0 => 'monday',
1 => 'tuesday',
2 => 'wednesday',
3 => 'thursday',
4 => 'friday',
5 => 'saturday',
6 => 'sunday'
);
# fix
$DT_Min = new DateTime( $whichWeek.(isset($Days[$FirstDay]) === TRUE ? $Days[$FirstDay] : $Days[6]).' '.$DateString);
$DT_Max = clone($DT_Min);
return array(
$DT_Min->format('Y-m-d'),
$DT_Max->modify('+6 days')->format('Y-m-d')
);
}
}
A simple code to return the days from start DateTime and end DateTime. Using gmdate() method you can format date/time.
$start_str_date = strtotime($start_date);
$end_str_date = strtotime($end_date);
$interval_days = $end_str_date - $start_str_date;
$days = gmdate('d',$interval_days);
echo $days;
I noticed that most of the answers here make use of strtotime/DateTime. While correct, personally I rather calculating dates without using English words.
Here's a simple solution that makes use of mtkime :
$now = time();
$day_of_week = (int)date('w', $now);
$week_start = mktime(0, 0, 0, date('n', $now), date('j', $now)-$day_of_week, date('Y', $now));
$week_end = mktime(23, 59, 59, date('n', $week_start), date('j', $week_start)+6, date('Y', $week_start));
function weekRange($year, $week){
$dateFrom = new \DateTime();
$dateFrom->setISODate($year, $week);
$dateTo = new \DateTime();
$dateTo->setISODate($year, $week, 7);
return array(
'week' => $dateFrom->format('Y-W'),
'start'=> $dateFrom->format('Y-m-d'),
'end' => $dateTo->format('Y-m-d')
);
}
Example:
$weekInformation = weekRange(2020, 38);
echo $weekInformation['start'];
// Display: 2020-09-14
echo $weekInformation['end'];
// Display: 2020-09-20
from PHP DateTime doc :
<?php
$date = new DateTime();
$date->setISODate(2008, 2);
$startDay = $date->format('Y-m-d');
$date->setISODate(2008, 2, 7);
$endDay = $date->format('Y-m-d');
?>

Categories