Php get the timestamp values grouped by months - php

Suppose that i have
$time1 = 1492894800 //23/04/2017
$time2 = 1503521999 //23/08/2017
I would like to get timestamps grouped by months such that
get timestamp with rangess between months preserving first and last month of $time1 and $time2 such that i should have
1 23/04/2017 to 30/04/2017
2 01/05/2017 - 31/05/2017
....... //continue full months and lastly
01/08/2017 - 23/08/2017
i have tried
$timearrays = $this->getMontTimestampRanges($time1, $time2);
public function getMontTimestampRanges($ts1, $ts2){
$start = (new DateTime(date("Y-m-d", $ts1)));
$end = (new DateTime(date("Y-m-d", $ts2)));
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($start, $interval, $end);
$timestamps = [];
foreach ($period as $dt) {
//am stuck here on how to group based on the months
..push to array
}
return $timestamps;
}
so the final array i would like it to be of the form:
$timestamps = [
0=>["from":, "to": ] //first month(april)
1=>[ ] //second month may
]
How do i go about this?

After clarifying your query on my last answer, I have decided to delete my answer and post a new answer.
$start = 1492894800; //23/04/2017
$end = 1503521999; //23/08/2017
$steps = date('Ym', $end) - date('Ym', $start);
$timestamps = array();
for($i = 0; $i <= $steps; $i++) {
$base = strtotime("+{$i} months", $start);
$timestamps[] = array(
'from' => $i == 0 ? date('Y-m-d', $start) : date('Y-m-01', $base),
'to' => $i == $steps ? date('Y-m-d', $end) : date('Y-m-t', $base)
);
// If we want timestamps
// $timestamps[] = array(
// 'from' => strtotime(date('Y-m-01', $base)),
// 'to' => strtotime(date('Y-m-t', $base))
// );
}
print_r($timestamps);
Ideone link

I edited your code
Try this:
<?php
$time1 = 1492894800 ;//23/04/2017
$time2 = 1503521999; //23/08/2017
$timearrays = getMontTimestampRanges($time1, $time2);
var_dump( $timearrays);
function getMontTimestampRanges($ts1, $ts2){
$start = new DateTime(date("Y-m-d", $ts1));
$end = new DateTime(date("Y-m-d", $ts2));
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);
$timestamps = [];
$startM = $period->getStartDate()->format('m');
$endM = $period->getEndDate()->format('m');
foreach ($period as $dt) {
//am stuck here on how to group based on the months
//start
if($startM == $dt->format('m'))
{
$timestamps[] = array('start'=>$start->format('Y-m-d'),'end'=>$dt->format('Y-m-t'));
}
elseif($endM == $dt->format('m'))
{
$timestamps[] = array('start'=>$dt->format('Y-m').'-01','end'=>$end->format('Y-m-d') );
}
else
{
$timestamps[] = array('start'=>$dt->format('Y-m').'-01','end'=>$dt->format('Y-m-t'));
}
}
return $timestamps;
}
http://sandbox.onlinephpfunctions.com/code/8527e45427fd0114f1e058fffc1885e460807a0a
Hope it helps.

Related

Calculate weekdays between two date

I want to calculate how many days in a Weekday. But it return "Uncaught Error: Call to a member function add() on integer".
Here my code
$dateStart_convert = DateTime::createFromFormat("d/m/Y", $cuti_sdate);
$start = $dateStart_convert->getTimestamp();
$dateEnd_convert = DateTime::createFromFormat("d/m/Y", $cuti_edate);
$end = $dateEnd_convert->getTimestamp();
$oneday = new DateInterval("P1D");
$workdays = array();
foreach(new DatePeriod($start, $oneday, $end->add($oneday)) as $day)
{
$day_num = $day->format("N"); /* 'N' number days 1 (mon) to 7 (sun) */
if($day_num < 6)
{
$workdays[] = $day->format("Y-m-d");
}
$weekday_date = array_merge(array_diff($workdays, $cuti_date));
$c_weekday = count($weekday_date);
}
use this :)
<?php
$start = new DateTime($startDate);
$end = new DateTime($endDate);
$oneday = new DateInterval("P1D");
$days = array();
$data = "7.5";
/* Iterate from $start up to $end+1 day, one day in each iteration.
We add one day to the $end date, because the DatePeriod only iterates up to,
not including, the end date. */
foreach(new DatePeriod($start, $oneday, $end->add($oneday)) as $day) {
$day_num = $day->format("N"); /* 'N' number days 1 (mon) to 7 (sun) */
if($day_num < 6) { /* weekday */
$days[$day->format("Y-m-d")] = $data;
}
}
$weekdays = count($days);
?>

How can I calculate date weekend in php

I have a date like this
$start = strtotime('2010-01-01'); $end = strtotime('2010-01-25');
My question:
How can I calculate or count weekend from $start & $end date range..??
A more modern approach is using php's DateTime class. Below, you get an array with week numbers as keys. I added the counts of weeks and weekend days.
<?php
$begin = new DateTime('2010-01-01');
$end = new DateTime('2010-01-25');
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval, $end);
$weekends = [];
foreach($daterange as $date) {
if (in_array($date->format('N'), [6,7])) {
$weekends[$date->format('W')][] = $date->format('Y-m-d');
}
}
print_r($weekends);
echo 'Number of weeks: ' . count($weekends);
echo 'Number of weekend days: ' . (count($weekends, COUNT_RECURSIVE) - count($weekends));
Note: if you're using PHP 5.3, use array() instead of block arrays [].
May be this code snippet will help:
<?php
//get current month for example
$beginday = date("Y-m-01");
$lastday = date("Y-m-t");
$nr_work_days = getWorkingDays($beginday, $lastday);
echo $nr_work_days;
function getWorkingDays($startDate, $endDate)
{
$begin = strtotime($startDate);
$end = strtotime($endDate);
if ($begin > $end) {
echo "startdate is in the future! <br />";
return 0;
} else {
$no_days = 0;
$weekends = 0;
while ($begin <= $end) {
$no_days++; // no of days in the given interval
$what_day = date("N", $begin);
if ($what_day > 5) { // 6 and 7 are weekend days
$weekends++;
};
$begin += 86400; // +1 day
};
$working_days = $no_days - $weekends;
return $working_days;
}
}
Another solution can be: (Get date range between two dates excluding weekends)
This might help maybe:
$start = strtotime('2010-01-01');
$end = strtotime('2010-01-25');
$differ = $end-$start;
$min = $differ/60;
$hrs = $min/60;
$days = $hrs/24;
$weeks = $days/7;
if(is_int($weeks))
$weeks++;
echo '<pre>';
print_r(ceil($weeks));
echo '</pre>';

Conversion of Date string to word issue PHP string

I am converting a string number to strtotime and then attempting to get a written date outputted. This is working to an extent but the issue is that the dates are wrong.
THE PHP
$today = date("Y-m-d");
function dateRange($start, $end) {
date_default_timezone_set('UTC');
$diff = strtotime($end) - strtotime($start);
$daysBetween = floor($diff/(60*60*24));
$formattedDates = array();
for ($i = 0; $i <= $daysBetween; $i++) {
// $tmpDate = date('Y-m-d', strtotime($start . " + $i days"));
$tmpDate = date('Y-m-d', strtotime($start . " + $i days"));
// $formattedDates[] = date('Y-m-d', strtotime($tmpDate));
$formattedDates[] = date('Y-m-d', strtotime($tmpDate));
}
return $formattedDates;
}
$start=$date_system_installed;
$end=$today;
$formattedDates = dateRange($start, $end);
foreach ($formattedDates as $dt)
{
$date = strtotime($dt);
echo date('l jS F Y',$date);
}
The outputted dates
The true dates that should be showing but in text
Where am i going wrong for this to output the correct format but incorrect dates?
Here's a date range function I wrote that generates an array of formatted dates. It uses the DateTime() functions which will give you more accurate intervals than things like 60*60/24.
/**
* Creates an array of dates between `$start` and `$end`, intervaled by a day
*
* #param string $start Start date string
* #param string $end End date string
* #param string $format Date format
* #param boolean $inclusive Whether or not to include the start and end dates
* #return array Array of dates between the two
*/
function dateRange($start = null, $end = null, $format = 'Y-m-d', $inclusive = true) {
if (empty($start) || empty($end)) {
return array();
}
$start = new DateTime($start);
$end = new DateTime($end);
if ($inclusive) {
$end = $end->modify('+1 day');
} else {
$start = $start->modify('+1 day');
}
$interval = new DateInterval('P1D');
$period = new DatePeriod($start, $interval, $end);
$daterange = array();
foreach ($period as $date) {
$daterange[] = $date->format($format);
}
return $daterange;
}
And a test case
function testDateRange() {
$results = dateRange('2012-02-20', '2012-03-01');
$expected = array(
'2012-02-20',
'2012-02-21',
'2012-02-22',
'2012-02-23',
'2012-02-24',
'2012-02-25',
'2012-02-26',
'2012-02-27',
'2012-02-28',
'2012-02-29',
'2012-03-01'
);
$this->assertEquals($expected, $results);
$results = dateRange('2012-02-24', '2012-03-01', 'M j');
$expected = array(
'Feb 24',
'Feb 25',
'Feb 26',
'Feb 27',
'Feb 28',
'Feb 29',
'Mar 1'
);
$this->assertEquals($expected, $results);
$results = dateRange('2012-02-25', '2012-03-01', 'Y-m-d', false);
$expected = array(
'2012-02-26',
'2012-02-27',
'2012-02-28',
'2012-02-29'
);
$this->assertEquals($expected, $results);
}
I ran your code - it's all ok
http://codepad.org/E18ccpxV

PHP: List of days between two dates [duplicate]

This question already has answers here:
PHP: Return all dates between two dates in an array [duplicate]
(26 answers)
Closed 4 years ago.
Is there an easy way to get a list of days between two dates in PHP?
I would like to have something like this in the end:
(pseudocode)
date1 = 29/08/2013
date2 = 03/09/2013
resultArray = functionReturnDates(date1, date2);
and the resulting array would contain:
resultArray[0] = 29/08/2013
resultArray[1] = 30/08/2013
resultArray[2] = 31/08/2013
resultArray[3] = 01/09/2013
resultArray[4] = 02/09/2013
resultArray[5] = 03/09/2013
for example.
$date1 = '29/08/2013';
$date2 = '03/09/2013';
function returnDates($fromdate, $todate) {
$fromdate = \DateTime::createFromFormat('d/m/Y', $fromdate);
$todate = \DateTime::createFromFormat('d/m/Y', $todate);
return new \DatePeriod(
$fromdate,
new \DateInterval('P1D'),
$todate->modify('+1 day')
);
}
$datePeriod = returnDates($date1, $date2);
foreach($datePeriod as $date) {
echo $date->format('d/m/Y'), PHP_EOL;
}
function DatePeriod_start_end($begin,$end){
$begin = new DateTime($begin);
$end = new DateTime($end.' +1 day');
$daterange = new DatePeriod($begin, new DateInterval('P1D'), $end);
foreach($daterange as $date){
$dates[] = $date->format("Y-m-d");
}
return $dates;
}
dunno if this is at all practical, but it works pretty straight-forward
$end = '2013-08-29';
$start = '2013-08-25';
$datediff = strtotime($end) - strtotime($start);
$datediff = floor($datediff/(60*60*24));
for($i = 0; $i < $datediff + 1; $i++){
echo date("Y-m-d", strtotime($start . ' + ' . $i . 'day')) . "<br>";
}
Try this:
function daysBetween($start, $end)
$dates = array();
while($start <= $end)
{
array_push(
$dates,
date(
'dS M Y',
$start
)
);
$start += 86400;
}
return $dates;
}
$start = strtotime('2009-10-20');
$end = strtotime('2009-10-25');
var_dump(daysBetween($start,$end));
$datearray = array();
$date = $date1;
$days = ceil(abs($date2 - $date1) / 86400) + 1;//no of days
for($i = 1;$i <= $days; $i++){
array_push($datearray,$date);
$date = $date+86400;
}
foreach($datearray as $days){
echo date('Y-m-d, $days);
}

Get date range between two dates excluding weekends

Given the following dates:
6/30/2010 - 7/6/2010
and a static variable:
$h = 7.5
I need to create an array like:
Array ( [2010-06-30] => 7.5 [2010-07-01] => 7.5 => [2010-07-02] => 7.5 => [2010-07-05] => 7.5 => [2010-07-06] => 7.5)
Weekend days excluded.
No, it's not homework...for some reason I just can't think straight today.
For PHP >= 5.3.0, use the DatePeriod class. It's unfortunately barely documented.
$start = new DateTime('6/30/2010');
$end = new DateTime('7/6/2010');
$oneday = new DateInterval("P1D");
$days = array();
$data = "7.5";
/* Iterate from $start up to $end+1 day, one day in each iteration.
We add one day to the $end date, because the DatePeriod only iterates up to,
not including, the end date. */
foreach(new DatePeriod($start, $oneday, $end->add($oneday)) as $day) {
$day_num = $day->format("N"); /* 'N' number days 1 (mon) to 7 (sun) */
if($day_num < 6) { /* weekday */
$days[$day->format("Y-m-d")] = $data;
}
}
print_r($days);
The simplest method:
$start = strtotime('6/30/2010');
$end = strtotime('7/6/2010');
$result = array();
while ($start <= $end) {
if (date('N', $start) <= 5) {
$current = date('m/d/Y', $start);
$result[$current] = 7.5;
}
$start += 86400;
}
print_r($result);
UPDATE: Forgot to skip weekends. This should work now.
This is gnud's answer but as a function (also added an option to exclude the current day from the calculation):
(examples below)
public function getNumberOfDays($startDate, $endDate, $hoursPerDay="7.5", $excludeToday=true)
{
// d/m/Y
$start = new DateTime($startDate);
$end = new DateTime($endDate);
$oneday = new DateInterval("P1D");
$days = array();
/* Iterate from $start up to $end+1 day, one day in each iteration.
We add one day to the $end date, because the DatePeriod only iterates up to,
not including, the end date. */
foreach(new DatePeriod($start, $oneday, $end->add($oneday)) as $day) {
$day_num = $day->format("N"); /* 'N' number days 1 (mon) to 7 (sun) */
if($day_num < 6) { /* weekday */
$days[$day->format("Y-m-d")] = $hoursPerDay;
}
}
if ($excludeToday)
array_pop ($days);
return $days;
}
And to use it:
$date1 = "2012-01-12";
$date2 = date('Y-m-d'); //today's date
$daysArray = getNumberOfDays($date1, $date2);
echo 'hours: ' . array_sum($daysArray);
echo 'days: ' . count($daysArray);
This is OOP approach, just in case. It returns an array with all of dates, except the weekends days.
class Date{
public function getIntervalBetweenTwoDates($startDate, $endDate){
$period = new DatePeriod(
new DateTime($startDate),
new DateInterval('P1D'),
new DateTime($endDate)
);
$all_days = array();$i = 0;
foreach($period as $date) {
if ($this->isWeekend($date->format('Y-m-d'))){
$all_days[$i] = $date->format('Y-m-d');
$i++;
}
}
return $all_days;
}
public function isWeekend($date) {
$weekDay = date('w', strtotime($date));
if (($weekDay == 0 || $weekDay == 6)){
return false;
}else{
return true;
}
}
}
$d = new Date();
var_dump($d->getIntervalBetweenTwoDates('2015-08-01','2015-08-08'));

Categories