Create an Array of the Last 30 Days Using PHP - php

I am trying to create an array starting with today and going back the last 30 days with PHP and I am having trouble. I can estimate but I don’t know a good way of doing it and taking into account the number of days in the previous month etc. Does anyone have a good solution? I can’t get close but I need to make sure it is 100% accurate.

Try this:
<?php
$d = array();
for($i = 0; $i < 30; $i++)
$d[] = date("d", strtotime('-'. $i .' days'));
?>

Here is advance latest snippet for the same,
$today = new DateTime(); // today
$begin = $today->sub(new DateInterval('P30D')); //created 30 days interval back
$end = new DateTime();
$end = $end->modify('+1 day'); // interval generates upto last day
$interval = new DateInterval('P1D'); // 1d interval range
$daterange = new DatePeriod($begin, $interval, $end); // it always runs forwards in date
foreach ($daterange as $date) { // date object
$d[] = $date->format("Y-m-d"); // your date
}
print_r($d);
Working demo.
Official doc.

For those who want to show sales of the past X days,
As asked in this closed question (https://stackoverflow.com/questions/11193191/how-to-get-last-7-days-using-php#=), this worked for me.
$sales = Sale::find_all();//the sales object or array
for($i=0; $i<7; $i++){
$sale_sum = 0; //sum of sale initial
if($i==0){
$day = strtotime("today");
} else {
$day = strtotime("$i days ago");
}
$thisDayInWords = strftime("%A", $day);
foreach($sales as $sale){
$date = strtotime($sale->date_of_sale)); //May 30th 2018 10:00:00 AM
$dateInWords = strftime("%A", $date);
if($dateInWords == $thisDayInWords){
$sale_sum += $sale->total_sale;//add only sales of this date... or whatever
}
}
//display the results of each day's sale
echo $thisDayInWords."-".$sale_sum; ?>
}
Before you get angry:
I placed this answer here to help someone who was directed here from that question. Couldn't answer there :(

You can use time to control the days:
for ($i = 0; $i < 30; $i++)
{
$timestamp = time();
$tm = 86400 * $i; // 60 * 60 * 24 = 86400 = 1 day in seconds
$tm = $timestamp - $tm;
$the_date = date("m/d/Y", $tm);
}
Now, within the for loop you can use the $the_date variable for whatever purposes you might want to. :-)

$d = array();
for($i = 0; $i < 30; $i++)
array_unshift($d,strtotime('-'. $i .' days'));

Related

I would like to put every other wednesday into an array using php

My Issue:
I have found a way to select every other Wednesday here: PHP Select every other Wednesday with the following code.
<?php
$number_of_dates = 10;
$start_date = new DateTime("1/1/20");
$interval = DateInterval::createFromDateString("second wednesday");
$period = new DatePeriod($start_date, $interval, $number_of_dates - 1);
foreach ($period as $date) {
$datex = $date->format("m-d-Y").PHP_EOL;
echo "$datex<br>";
}
?>
What I need to do is put every other Wednesday into an array.
I can put a range of dates into an array, but it uses every day in the range with the following code. I just need it to be every other Wednesday. How can I do this?
<?PHP
$dates = array();
$datetime1 = new DateTime("2020-01-01");
$datetime2 = new DateTime("2020-1-31");
$interval = $datetime1->diff($datetime2);
$days = (int) $interval->format('%R%a');
$currentTimestamp = $datetime1->getTimestamp();
$dates[] = date("m/d/Y", $currentTimestamp);
for ($x = 0; $x < $days; $x++)
{
$currentTimestamp = strtotime("+1 day", $currentTimestamp);
$dates[] = date("m/d/Y", $currentTimestamp);
}
print_r($dates);
?>
Try this :
<?php
$dates = array();
$datetime = new DateTime();
for ($i = 0; $i < 52; $i++) {
$datetime->modify('next Wednesday');
array_push($dates, $datetime->format('m/d/Y'));
}
print_r($dates);
What does it do ?
it gets the current time (you can customize this in the new
Datetime),
then loops for 52 times (you can customize this too in the for loop),
then finds the next wednesday using modify.
Live Demo :
http://sandbox.onlinephpfunctions.com/code/57c6a6b682a07f75bc1c507c588c844d84330610
Regards
Your first snippet is already outputting the right set of dates, so you just would need to put each of those in an array, instead of echoing them.
(Although I don't know if it's really necessary to do so, since you can already loop over the $period variable - but it depends exactly what you plan to do with the data afterwards).
Example:
$number_of_dates = 10;
$start_date = new DateTime("1/1/20");
$interval = DateInterval::createFromDateString("second wednesday");
$period = new DatePeriod($start_date, $interval, $number_of_dates - 1);
$dates = array(); //declare a new empty array
foreach ($period as $date) {
$dates[] = $date; //add the date to the next empty array index
}
var_dump($dates);
Or if you actually want an array containing the string representations of those dates, in that specific format, then:
$dates2 = array();
foreach ($period as $date) {
$dates2[] = $date->format("m-d-Y");
}
var_dump($dates2);
Live demo: http://sandbox.onlinephpfunctions.com/code/9e58e552edff204ae6df3ca9b437b8c597edf2b3
Give it a try
<?PHP
$dates = [];
$datetime1 = new DateTime("2020-01-01");
$datetime2 = new DateTime("2020-01-31");
$datetime1->modify('wednesday'); // Start with wednesday
while($datetime1 < $datetime2){
$dates[] = $datetime1->format('Y-m-d');
$datetime1->modify('second wednesday'); // Other Wednesday
}
print_r($dates);
?>

Find the week start and end dates of all weeks between two week numbers

I am trying to get the start date and end dates of all weeks between two week numbers.
That is one of my date is 2014-05-17 and its week number is 20 and other date is 2014-08-13 and its week number is 33.
My task is to get start and end dates of all weeks between 20 and 33. Here Sunday is the week start and Saturday week end.
$signupweek='2014-05-17';
$signupweek=date("W",strtotime($signupdate));
//week number of current date.
$weekNumber = date("W");
Can anyone help to find the dates.
try this
$signupdate='2014-05-17';
$signupweek=date("W",strtotime($signupdate));
$year=date("Y",strtotime($signupdate));
$currentweek = date("W");
for($i=$signupweek;$i<=$currentweek;$i++) {
$result=getWeek($i,$year);
echo "Week:".$i." Start date:".$result['start']." End date:".$result['end']."<br>";
}
function getWeek($week, $year) {
$dto = new DateTime();
$result['start'] = $dto->setISODate($year, $week, 0)->format('Y-m-d');
$result['end'] = $dto->setISODate($year, $week, 6)->format('Y-m-d');
return $result;
}
Output
Week:20 Start date:2014-05-11 End date:2014-05-17
Week:21 Start date:2014-05-18 End date:2014-05-24
Week:22 Start date:2014-05-25 End date:2014-05-31
Week:23 Start date:2014-06-01 End date:2014-06-07
Week:24 Start date:2014-06-08 End date:2014-06-14
Week:25 Start date:2014-06-15 End date:2014-06-21
Week:26 Start date:2014-06-22 End date:2014-06-28
Week:27 Start date:2014-06-29 End date:2014-07-05
Week:28 Start date:2014-07-06 End date:2014-07-12
Week:29 Start date:2014-07-13 End date:2014-07-19
Week:30 Start date:2014-07-20 End date:2014-07-26
Week:31 Start date:2014-07-27 End date:2014-08-02
Week:32 Start date:2014-08-03 End date:2014-08-09
Week:33 Start date:2014-08-10 End date:2014-08-16
Another method...
If you have a date, from that date you can find the start date and end date of that week. But here week number is not used.
For example:
You have a date 2014-08-13, then required start date is 2014-08-10 and end date is 2014-08-16.
PHP code is
$signupweek='2014-8-13';
/*start day*/
for($i = 0; $i <7 ; $i++)
{
$date = date('Y-m-d', strtotime("-".$i."days", strtotime($signupweek)));
$dayName = date('D', strtotime($date));
if($dayName == "Sun")
{
echo "start day is ". $date."<br>";
}
}
/*end day*/
for($i = 0; $i <7 ; $i++)
{
$date = date('Y-m-d', strtotime("+".$i."days", strtotime($signupweek)));
$dayName = date('D', strtotime($date));
if($dayName == "Sat")
{
echo "end day is ". $date."<br>";
}
}
OUTPUT
start day is 2014-08-10
end day is 2014-08-16
Hope this is useful..
Here's an example that implements the function from this answer:
$signupweek = '2014-05-17';
$signupweek = date("W", strtotime($signupweek));
$current_week = date('W');
$output = array();
// Loop through the weeks BETWEEN your given weeks
// to include the start and end week, remove the +1 below and make
// it $i <= $current_week
for($i = $signupweek + 1; $i < $current_week; $i++) {
// Get the start and end for the current week ($i)
$dates = getStartAndEndDate($i, '2014');
// if the start or end of the week is greater than now, skip it
if(strtotime($dates['start']) > time() or strtotime($dates['end']) > time())
continue;
// Add to output array
$output[] = $dates;
}
function getStartAndEndDate($week, $year)
{
$time = strtotime("1 January $year", time());
$day = date('w', $time);
$time += ((7 * $week) + 1 - $day) * 24 * 3600;
$return['start'] = date('Y-n-j', $time);
$time += 6 * 24 * 3600;
$return['end'] = date('Y-n-j', $time);
return $return;
}
Output
Try this:
$startTime = "2014-05-17";
$startWeek = 20;
$endWeek = 33;
for ($i = 0; $i <= ($endWeek - $startWeek); $i++) {
$days = $i * 7;
echo date("Y-m-d", strtotime($startTime . "+$days day")).'<br />';
}
Unfortunately, it seems that 2014-08-13 is not the start of week 33. 2014-08-16 is.
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")];
}
print_r( getDateRangeForWeek("2016-05-07") );
print_r( getDateRangeForAllWeeks("2015-11-07", "2016-02-15") );

Create a table with day of month as headers. PHP

I want to create a table like this...
Oct-01 | Oct-02 | Oct-03 | Oct-04 | etc etc
Using whatever month it is now.
I'm using this to get the first day...
$first = date('01-m-Y',strtotime('this month'));
How can I increment this by the amount of days in this month?
Use cal_days_in_month(CAL_GREGORIAN, date(j), 2013)?
But how to increment the first day.
I tried using '+1 day' in the strtotime, but nothing happened.
Any ideas?
PHP's DateTime class can be used here. You don't need to use cal_days_in_month function to calculate the number of days in a month -- DateTime handles it automatigically. And it's a lot more cleaner and supports a wide range of dates.
Here's how:
$start = new DateTime('first day of this month');
$end = new DateTime('first day of this month + 1 month');
$period = new DatePeriod($start, new DateInterval('P1D'), $end);
foreach($period as $day){
echo $day->format('M-d')."<br/>";
}
Demo!
I prefer using the DateTime object:
$date = new DateTime();
$date->modify('first day of this month');
$days = array();
for($i = 1; $i <= $date->format('t'); $i++){
$days[] = $date->format('M-d');
$date->modify('+1 day');
}
You could also add the whole date object to the array giving you flexibility later to use it however you want.
<?php
$days = array();
$maxDay = cal_days_in_month(CAL_GREGORIAN, date('j'), date('Y'));
for($i = 1; $i<$maxDay; ++$i) {
$days[] = sprintf(date('M')."-%1$02d", $i);
}
echo "<pre>";
var_dump($days);
Now you can do whatever you like with $days array...
http://phpfiddle.org/lite/code/fd1-1r2

PHP- Display days weekly by giving 2 dates

I'd like display dates by week number between giving 2 dates like example below. Is this possible in PHP?
if the dates are 2010-12-01 thru 2010-12-19, it will display it as follows.
week-1
2010-12-01
2010-12-02
2010-12-03
2010-12-04
2010-12-05
2010-12-06
2010-12-07
week-2
2010-12-08
2010-12-09
2010-12-10
2010-12-11
2010-12-12
2010-12-13
2010-12-14
week-3
2010-12-15
2010-12-16
2010-12-17
2010-12-18
2010-12-19
and so on...
I use mysql. It has startdate end enddate fields.
thank you in advance.
I can get how many weeks in those giving 2 dates and display them using a
datediff('ww', '2010-12-01', '2010-12-19', false); I found on the internet.
And I can display dates between two dates as follows. But I am having trouble grouping them by week.
$sdate = "2010-12-01";
$edate = "2010-12-19";
$days = getDaysInBetween($sdate, $edate);
foreach ($days as $val)
{
echo $val;
}
function getDaysInBetween($start, $end) {
// Vars
$day = 86400; // Day in seconds
$format = 'Y-m-d'; // Output format (see PHP date funciton)
$sTime = strtotime($start); // Start as time
$eTime = strtotime($end); // End as time
$numDays = round(($eTime - $sTime) / $day) + 1;
$days = array();
// Get days
for ($d = 0; $d < $numDays; $d++) {
$days[] = date($format, ($sTime + ($d * $day)));
}
// Return days
return $days;
}
New answer.
$current_date = strtotime('2010-12-01');
$end_date = strtotime('2010-12-19');
$day_count = 0;
$current_week = null;
do {
if ((int)($day_count / 7) + 1 != $current_week) {
$current_week = (int)($day_count / 7) + 1;
echo 'week-'.$current_week.'<br />';
}
echo date('Y-m-d', $current_date).'<br />';
$current_date = strtotime('+1 day', $current_date);
$day_count ++;
} while ($current_date <= $end_date);
You will definitely need this: Simplest way to increment a date in PHP?. Write a forloop and increment the day every time. You will also need the DateTime class and functions as date. Indeed asking for date('W', yourDateHere) is a nice idea.
You will get something like this (pseudocode)
$startDate;
$endDate;
$nrOfDays = dateDiffInDays($endDate, $startDate);
$currentWeek = date('W',$startDate);
for($i = 0; $i < $nrOfDays; $i++)
{
$newDay = date('+$i day', $startDate); // get the incremented day
$newWeek = date('W', $newDay); // get the week of the new day
if($newWeek != $currentWeek) // check if we must print the new week, or if we are still in the current
print $newWeek;
print $newDay; // print the day
}
Hope this helps. Good luck.
Tools sufficient to do the job:
strtotime('2010-11-23') - to get a timestamp from a date
strtotime('+1 day', $someTimestamp) - to get the next day
date('W', $someTimestamp) - to get the week number (if you want to group by ISO week number)
array_chunk($orderedListOfSuccessiveDates, 7) - to split in groups of seven days (if you don't want to group by ISO week number)
Warning: Never, ever increment days by adding 86400 to the timestamp! That is the easiest way to break everything when Daylight Saving comes along. Either use the strtotime function or the DateTime class.
Here you go. Although this is with weeks starting on sundays (just change it to monday if need be). And it doesnt work if the dates arent in the same year. But it should be pretty easy to fix that. If not_same_year then ...
$start_date = mktime(0, 0, 0, 12, 01, 2010);
$start_date_week_number = (int) date("W", $start_date);
$end_date = mktime(0, 0, 0, 12, 19, 2010);
$end_date_week_number = (int) date("W", $end_date);
$n = $start_date_week_number;
$w = 1;
$date = $start_date;
while($n <= $end_date_week_number) {
echo("<strong>Week " . $w . "</strong><br />");
$s = 0;
$e = 6;
if($n == $start_date_week_number) $s = (int) date("w", $start_date);
elseif($n == $end_date_week_number) $e = (int) date("w", $end_date);
while($s <= $e) {
echo(date("j-m-y", $date) . "<br />");
$c_date = getdate($date);
$date = mktime($c_date['hours'], $c_date['minutes'], $c_date['seconds'], $c_date['mon'], $c_date['mday'] + 1, $c_date['year']);
$s++;
}
$n++; $w++;
}
DEMO HERE
Edit: just fixed it when I realized you wanted to count the weeks (not get the actual week number)...
$startDate = new DateTime('2010-01-01');
$endDate = new DateTime('2010-01-14');
$weeksDays = getWeeksDaysBetween($startDate, $endDate);
foreach($weeksDays as $week => $days)
{
echo "Week $week<ul>";
foreach($days as $day){
echo "<li>$day</li>";
}
echo "</ul>";
}
function getWeeksDaysBetween($startDate, $endDate)
{
$weeksDays = array();
$dateDiff = $endDate->diff($startDate);
$fullDays = $dateDiff->d;
$numWeeks = floor($fullDays / 7) + 1;
$weeksDays[1][] = $startDate->format('Y-m-d');
for ($i = 1; $i <= $fullDays; $i++)
{
$weekNum = floor($i / 7) + 1;
$dateInterval = DateInterval::createFromDateString("1 day");
$weeksDays[$weekNum][] = $startDate->add($dateInterval)->format('Y-m-d');
}
return $weeksDays;
}

PHP: get next 13 dates from date?

I am trying to get an array of a date plus the next 13 dates to get a 14 day schedule starting from a given date.
here is my function:
$time = strtotime($s_row['schedule_start_date']); // 20091030
$day = 60*60*24;
for($i = 0; $i<14; $i++)
{
$the_time = $time+($day*$i);
$date = date('Y-m-d',$the_time);
array_push($dates,$date);
}
But it seems to be repeating a date when the month switches over..
this is what I get:
2009-10-30|2009-10-31|2009-11-01|2009-11-01|2009-11-02|2009-11-03|2009-11-04|2009-11-05|2009-11-06|2009-11-07|2009-11-08|2009-11-09|2009-11-10|2009-11-11
Notice that 2009-11-01 is repeated. I cannot figure out why?
What am I doing wrong?
Thanks!!
I would use strtotime
$start = strtotime($s_row['schedule_start_date']);
$dates=array();
for($i = 1; $i<=14; $i++)
{
array_push($dates,date('Y-m-d', strtotime("+$i day", $start)));
}
print_r($dates);
You have the same date because of daylight saving time switch. It's not safe to add 24*60*60 seconds to find next day, because 2 days in the year have more/less seconds in them. When you switch from summer to winter time you are adding 1 hour to a day. So it'll be 25*60*60 seconds in that day, that's why it's not switched in your code.
You can do your calculation by mktime(). For example:
## calculate seconds from epoch start for tomorrow
$tomorrow_epoch = mktime(0, 0, 0, date("m"), date("d")+1, date("Y"));
## format result in the way you need
$tomorrow_date = date("M-d-Y", $tomorrow_epoch);
Or the full version for your code:
$dates = array();
$now_year = date("Y");
$now_month = date("m");
$now_day = date("d");
for($i = 0; $i < 14; $i++) {
$next_day_epoch = mktime(0, 0, 0, $now_month, $now_day + $i, $now_year);
array_push(
$dates,
date("Y-m-d", $next_day_epoch)
);
}
I recommend something like:
for($i=1;$i<=14;$i++){
echo("$i day(s) away: ".date("m/d/Y",strtotime("+$i days")));
}

Categories