Conversion of Date string to word issue PHP string - php

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

Related

Php get the timestamp values grouped by months

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.

Get month name using start date and end date?

$startDate = "2014-03-01";
$endDate= "2014-05-25";
Result required: March, April, May;
for that PHP delivers the DatePeriod object. Just have a look at the following example.
$period = new DatePeriod(
new DateTime('2014-03-01'),
DateInterval::createFromDateString('1 month'),
new DateTime('2014-05-25')
);
foreach ($period as $month) {
echo strftime('%B', $month->format('U'));
}
A quick solution is to parse each day and check it month:
$startDate = "2014-03-01";
$endDate = "2014-05-25";
$start = strtotime($startDate);
$end = strtotime($endDate);
$result = array();
while ( $start <= $end )
{
$month = date("M", $start);
if( !in_array($month, $result) )
$result[] = $month;
$start += 86400;
}
print_r($result);
I believe it can be done much efficient by new OOP (DateTime object) approach, but this is fast and no-brain if you need to make it work.
<?php
$startDate = "2014-03-01";
echo date('F',strtotime($startDate));
?
$date = date('F',strtotime($startDate));
For full month representation (ie Januaray, February, etc)
$date = date('M',strtotime($startDate));
For abbreviated...(ie Jan, Feb, Mar)
REFERENCE
If you wanna echo out those months in between based on two dates....
$d = "2014-03-01";
$startDate = new DateTime($d);
$endDate = new DateTime("2014-05-01");
function diffInMonths(DateTime $date1, DateTime $date2)
{
$diff = $date1->diff($date2);
$months = $diff->y * 12 + $diff->m + $diff->d / 30;
return (int) round($months);
}
$t = diffInMonths($startDate, $endDate);
for($i=0;$i<$t+1;$i++){
echo date('F',strtotime($d. '+'.$i.' Months'));
}
PHP SANDBOX EXAMPLE

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'));

I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?

I'm starting with a date 2010-05-01 and ending with 2010-05-10. How can I iterate through all of those dates in PHP?
$begin = new DateTime('2010-05-01');
$end = new DateTime('2010-05-10');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);
foreach ($period as $dt) {
echo $dt->format("l Y-m-d H:i:s\n");
}
This will output all days in the defined period between $start and $end. If you want to include the 10th, set $end to 11th. You can adjust format to your liking. See the PHP Manual for DatePeriod. It requires PHP 5.3.
This also includes the last date
$begin = new DateTime( "2015-07-03" );
$end = new DateTime( "2015-07-09" );
for($i = $begin; $i <= $end; $i->modify('+1 day')){
echo $i->format("Y-m-d");
}
If you dont need the last date just remove = from the condition.
Converting to unix timestamps makes doing date math easier in php:
$startTime = strtotime( '2010-05-01 12:00' );
$endTime = strtotime( '2010-05-10 12:00' );
// Loop between timestamps, 24 hours at a time
for ( $i = $startTime; $i <= $endTime; $i = $i + 86400 ) {
$thisDate = date( 'Y-m-d', $i ); // 2010-05-01, 2010-05-02, etc
}
When using PHP with a timezone having DST, make sure to add a time that is not 23:00, 00:00 or 1:00 to protect against days skipping or repeating.
Copy from php.net sample for inclusive range:
$begin = new DateTime( '2012-08-01' );
$end = new DateTime( '2012-08-31' );
$end = $end->modify( '+1 day' );
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);
foreach($daterange as $date){
echo $date->format("Ymd") . "<br>";
}
Here is another simple implementation -
/**
* Date range
*
* #param $first
* #param $last
* #param string $step
* #param string $format
* #return array
*/
function dateRange( $first, $last, $step = '+1 day', $format = 'Y-m-d' ) {
$dates = [];
$current = strtotime( $first );
$last = strtotime( $last );
while( $current <= $last ) {
$dates[] = date( $format, $current );
$current = strtotime( $step, $current );
}
return $dates;
}
Example:
print_r( dateRange( '2010-07-26', '2010-08-05') );
Array (
[0] => 2010-07-26
[1] => 2010-07-27
[2] => 2010-07-28
[3] => 2010-07-29
[4] => 2010-07-30
[5] => 2010-07-31
[6] => 2010-08-01
[7] => 2010-08-02
[8] => 2010-08-03
[9] => 2010-08-04
[10] => 2010-08-05
)
$startTime = strtotime('2010-05-01');
$endTime = strtotime('2010-05-10');
// Loop between timestamps, 1 day at a time
$i = 1;
do {
$newTime = strtotime('+'.$i++.' days',$startTime);
echo $newTime;
} while ($newTime < $endTime);
or
$startTime = strtotime('2010-05-01');
$endTime = strtotime('2010-05-10');
// Loop between timestamps, 1 day at a time
do {
$startTime = strtotime('+1 day',$startTime);
echo $startTime;
} while ($startTime < $endTime);
User this function:-
function dateRange($first, $last, $step = '+1 day', $format = 'Y-m-d' ) {
$dates = array();
$current = strtotime($first);
$last = strtotime($last);
while( $current <= $last ) {
$dates[] = date($format, $current);
$current = strtotime($step, $current);
}
return $dates;
}
Usage / function call:-
Increase by one day:-
dateRange($start, $end); //increment is set to 1 day.
Increase by Month:-
dateRange($start, $end, "+1 month");//increase by one month
use third parameter if you like to set date format:-
dateRange($start, $end, "+1 month", "Y-m-d H:i:s");//increase by one month and format is mysql datetime
For Carbon users
use Carbon\Carbon;
$startDay = Carbon::parse("2021-08-01");
$endDay= Carbon::parse("2021-08-05");
$period = $startDay->range($endDay, 1, 'day');
When I print the data
[
Carbon\Carbon #1627790400 {#4970
date: 2021-08-01 00:00:00.0 America/Toronto (-04:00),
},
Carbon\Carbon #1627876800 {#4974
date: 2021-08-02 00:00:00.0 America/Toronto (-04:00),
},
Carbon\Carbon #1627963200 {#4978
date: 2021-08-03 00:00:00.0 America/Toronto (-04:00),
},
Carbon\Carbon #1628049600 {#5007
date: 2021-08-04 00:00:00.0 America/Toronto (-04:00),
},
Carbon\Carbon #1628136000 {#5009
date: 2021-08-05 00:00:00.0 America/Toronto (-04:00),
},
]
This is Laravel data dump using dd($period->toArray());. You can now iterate through $period if you want with a foreach statement.
One important note - it includes both the edge dates provided to method.
For more cool date related stuff, do check out the Carbon docs.
here's a way:
$date = new Carbon();
$dtStart = $date->startOfMonth();
$dtEnd = $dtStart->copy()->endOfMonth();
$weekendsInMoth = [];
while ($dtStart->diffInDays($dtEnd)) {
if($dtStart->isWeekend()) {
$weekendsInMoth[] = $dtStart->copy();
}
$dtStart->addDay();
}
The result of $weekendsInMoth is array of weekend days!
If you're using php version less than 8.2 and don't have the DatePeriod::INCLUDE_END_DATE const. I wrote a method that returns an array of \DateTimeImmutable.
This works with a start date before, the same or after the end date.
/**
* #param DateTimeImmutable $start
* #param DateTimeImmutable $end
* #return array<\DateTimeImmutable>
*/
public static function getRangeDays(\DateTimeImmutable $start, \DateTimeImmutable $end): array
{
$startDate = $start;
$endDate = $end;
$forwards = $endDate >= $startDate;
$carryDate = $startDate;
$days = [];
while (true) {
if (($forwards && $carryDate > $end) || (!$forwards && $carryDate < $end)) {
break;
}
$days[] = $carryDate;
if ($forwards) {
$carryDate = $carryDate->modify('+1 day');
} else {
$carryDate = $carryDate->modify('- 1 day');
}
}
return $days;
}
$date = new DateTime($_POST['date']);
$endDate = date_add(new DateTime($_POST['date']),date_interval_create_from_date_string("7 days"));
while ($date <= $endDate) {
print date_format($date,'d-m-Y')." AND END DATE IS : ".date_format($endDate,'d-m-Y')."\n";
date_add($date,date_interval_create_from_date_string("1 days"));
}
You can iterate like this also, The $_POST['date'] can be dent from your app or website
Instead of $_POST['date'] you can also place your string here "21-12-2019". Both will work.
<?php
$start_date = '2015-01-01';
$end_date = '2015-06-30';
while (strtotime($start_date) <= strtotime($end_date)) {
echo "$start_daten";
$start_date = date ("Y-m-d", strtotime("+1 days", strtotime($start_date)));
}
?>
If you use Laravel and want to use Carbon the correct solution would be the following:
$start_date = Carbon::createFromFormat('Y-m-d', '2020-01-01');
$end_date = Carbon::createFromFormat('Y-m-d', '2020-01-31');
$period = new CarbonPeriod($start_date, '1 day', $end_date);
foreach ($period as $dt) {
echo $dt->format("l Y-m-d H:i:s\n");
}
Remember to add:
use Carbon\Carbon;
use Carbon\CarbonPeriod;

Categories