Determining percentages and past seven days - php

I am coming here with a fairly simple (i think) question today. I would like to figure out the past seven days with php
So: I have todays date in variables (like $day = 2, $month = 5, $year = 2013, all put together 2/5/2013), My question is How would i go about getting the past seven days (in the same format) such as in this case
2/5/2013
1/5/2013
30/4/2013
29/4/2013
28/4/2013
27/4/2013
26/4/2013
I have tried subtracting the days for each variable (like $day6 = $todays_date - 1;) but getting month and year changes from that would be quite difficult i believe.
any answers would be appreciated.

Use DateTime class and its modify method
$date = new DateTime();
$yesterday = $date->modify('-1 day');

You could use mktime, and subtract the number of seconds for each day:
$today = mktime(0,0,0,$month,$day,$year);
for($i=0;$i<=6;$i++){
echo date('j/n/Y',$today-($i*(24*60*60))) . '<br />;
}

Try this:
$day = '02/05/2013';
$dates = array();
for($i = 0; $i < 7; $i++){
$dates[] = date('Y-m-d', strtotime($day . ' -' . $i . 'days'));
}
print_r('<pre>');
print_r($dates);
die();

Related

Is adding seconds wrong way to browse through the time in PHP?

I iterate through time by adding 86400 (the count of seconds in the 1 day) to list the dates.
define("DAY_SEC", 86400);
for ($i = strtotime("2016-10-01"); $i<=strtotime("2016-11-05"); $i = $i + DAY_SEC){
echo Date("Y-m-d, H:i:s", $i). ' = '. $i . '<br/>';
}
But look on the date "2016-10-30". It is there twice but with different hours
2016-10-28, 00:00:00 = 1477605600
2016-10-29, 00:00:00 = 1477692000
2016-10-30, 00:00:00 = 1477778400 <- here
2016-10-30, 23:00:00 = 1477864800 <- here
2016-10-31, 23:00:00 = 1477951200
What do I wrong?
thanx
Do not add or subtract or do any other math with timestamps to calculate past or future dates. Your code will fail after 2016-11-05 in U.S. and some other time zones because that is the end of Daylight Saving Time this year. strtotime() is aware of this, so use it with "+1 day" or something similar:
for ($i = strtotime("2016-10-01"); $i<=strtotime("2016-11-05"); $i = strtotime("+1 day", $i)){
echo Date("Y-m-d, H:i:s", $i). ' = '. $i . '<br/>';
}
It turns out 2016-10-30 is the end of Daylight Saving Time in many other places, so the time zone you are using is subject to that change.
It is called DST(Daylight Savings Time). Try using strtotime().
$start = strtotime("2016-10-01");
$end = strtotime("2016-11-05");
$interval = 1; //in days
for ($i = $start; $i<=$end; $i = $i + strtotime("+".$interval." days", $i)){
echo Date("Y-m-d, H:i:s", $i). ' = '. $i . '<br/>';
}

Add weeks in decimal value in php

I am trying to add weeks in decimal values like 1.5, 2.5 to date through strtotime() function. But its not giving correct result. I am using it like:
$start_date = "2015-01-01";
$date = strtotime(date("Y-m-d", strtotime($start_date)) . " +3.5 weeks");
$date = date("Y-m-d",$date);
echo $date;
And its giving 2015-02-04 as output. When added non decimal values like:
$date = strtotime(date("Y-m-d", strtotime($start_date)) . " +3 weeks");
It gives perfect results.
Any thought on it?
$date = '2015-01-01';
$weeks = "2,3,4,4.5";
foreach(explode(",", $weeks) as $week) {
print $week."\n";
$hours = $week * 24 * 7;
print $hours."\n";
print date("Y-m-d", strtotime("{$date} +{$hours} hours"))."\n";
}
You can use this logic, multiply your week decimal or not like 1,2,2.5,3,3.5 and multiply it by the amount of hours in a week :
$week = 2.5;
$desired = '+ '.$week*168.' hours';
$date = strtotime($desired, $start_date);
However, why playing with strings when you can just play with hours or seconds integers and doing a simple addition ?

Year, number of week and day of week to date in php

I have three pieces of information extracted from my database, the year, the number of week (1-52), and the day of week (mon, tue, wed). And I need to convert it in to a date.
How would I go about doing that in php?
Try this :
$yr="2014";
$week="01";
$day = "Mon";
echo date("Y-m-d", strtotime($yr."W".$week."D ".$day));
PHP fiddle:http://phpfiddle.org/main/code/nzg-ws6
Did a little digging and it looks like the day will need to be in numerical format for the strtotime conversion to work properly. Using a string such as 'Monday' won't work.
$yr = "2014";
$week = "01";
$day = "1"; //Monday
echo date("Y-m-d", strtotime($yr . "W" . $week . $day)); // "2014W011"
Note that I didn't include the 'D' prefix for the day as this looks to be following ISO8601.
Swapping your days to numbers can be done a few ways:
You could make an array Monday to Sunday and use the array key, or maybe a little easier you could do something like this:
$day date("N", strtotime("Monday")); // will echo 1
So the full code could look something like this:
$yr = "2014";
$week = "01";
$day = date("N", strtotime("Monday")); //
echo date("Y-m-d", strtotime($yr . "W" . $week . $day)); // "2014W011"
Here is a demo to check: http://3v4l.org/EllgQ
This converts you $day value to desired day format.
try this
$yr="2011";
$week="01";
$day="Monday";
$day=date("D",strtotime($day));
echo date("Y-m-d", strtotime($yr."W".$week."D ".$day));;
Demo

PHP get 4 months of dates using foreach

How would i get 4 months worth of dates from today using for each. I want to display the next 4 months of dates from today and format each one using foreach. Any ideas on how to do this.
Marvellous
$date = time();
$endDate = strtotime('+4 months');
while ($date < $endDate) {
echo date('j/n/Y', $date).'<br />';
$date += 86400; // 1 day
}
$ds = range(1,120);
foreach( $ds as $d){
echo date('Y-m-d', strtotime("today + $d day"));
}
This'll work if you are happy to guess that 4 months is 120 days away

How to find first day of the next month and remaining days till this date with PHP

How can I find first day of the next month and the remaining days till this day from the present day?
Thank you
Create a timestamp for 00:00 on the first day of next month:
$firstDayNextMonth = strtotime('first day of next month');
The number of days til that date is the number of seconds between now and then divided by (24 * 60 * 60).
$daysTilNextMonth = ($firstDayNextMonth - time()) / (24 * 3600);
$firstDayNextMonth = date('Y-m-d', strtotime('first day of next month'));
For getting first day after two months from current
$firstDayAfterTwoMonths = date('Y-m-d', strtotime('first day of +2 month'));
You can use DateTime object like this to find out the first day of next month like this:
$date = new DateTime('first day of next month');
You can do this to know how many days left from now to the first day of next month:
$date = new DateTime('now');
$nowTimestamp = $date->getTimestamp();
$date->modify('first day of next month');
$firstDayOfNextMonthTimestamp = $date->getTimestamp();
echo ($firstDayOfNextMonthTimestamp - $nowTimestamp) / 86400;
The easiest and quickest way is to use strtotime() which recognizes 'first day next month';
$firstDayNextMonth = date('Y-m-d', strtotime('first day next month'));
Since I googled this and came to this answer, I figured I'd include a more modern answer that works for PHP 5.3.0+.
//Your starting date as DateTime
$currentDate = new DateTime(date('Y-m-d'));
//Add 1 month
$currentDate->add(new DateInterval('P1M'));
//Get the first day of the next month as string
$firstDayOfNextMonth = $currentDate->format('Y-m-1');
You can get the first of the next month with this:
$now = getdate();
$nextmonth = ($now['mon'] + 1) % 13 + 1;
$year = $now['year'];
if($nextmonth == 1)
$year++;
$thefirst = gmmktime(0, 0, 0, $nextmonth, $year);
With this example, $thefirst will be the UNIX timestamp for the first of the next month. Use date to format it to your liking.
This will give you the remaining days in the month:
$now = getdate();
$months = array(
31,
28 + ($now['year'] % 4 == 0 ? 1 : 0), // Support for leap years!
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
);
$days = $months[$now['mon'] - 1];
$daysleft = $days - $now['mday'];
The number of days left will be stored in $daysleft.
Hope this helps!
$firstDayNextMonth = date('Y-m-d', mktime(0, 0, 0, date('m')+1, 1, date('Y')));
As another poster has mentioned the DateInterval object does not give accurate results for the next month when you use dates such as 1/31/2016 or 8/31/2016 as it skips the next month. My solution was to still use the DateInterval object but reformat your current date to be the first day of the current month prior to utilizing the DateInterval.
$currentDate = '8/31/2016';
$date = new DateTime(date("n", strtotime($currentDate))."/1/".date("Y", strtotime($currentDate)));
//add 1 month
$date->add(new DateInterval('P1M'));
$currentDate=$date->format('m/1/Y');
echo($currentDate);
easiest way to get the last day of the month
date('Y-m-d', mktime(0, 0, 0, date('m')+1, 1, date('Y')));
I took mattbasta's approach because it's able to get the 'first day of next month' with a given date, but there is a tiny problem in calculating the $nextmonth. The fix is as below:
$now = getdate();
$nextmonth = ($now['mon'] + 1) % 13 + 1;
$year = $now['year'];
if($nextmonth == 1)
$year++;
else
$nextmonth--;
$thefirst = gmmktime(0, 0, 0, $nextmonth, $year);
I initially thought about using a DateInterval object (as discussed above in another answer) but it is not reliable. For example, if the current DateTime is 31 January and then we add on a month (to get the next month) then it will skip February completely!
Here is my solution:
function start_of_next_month(DateTime $datetime)
{
$year = (int) $datetime->format('Y');
$month = (int) $datetime->format('n');
$month += 1;
if ($month === 13)
{
$month = 1;
$year += 1;
}
return new DateTime($year . '-' . $month . '-01');
}
Even easier way to get first and last day of next month
$first = strttotime("first day of next month");
$last = strttotime("last day of next month");
You could do something like this. To have this functionality, you need to make use of a php library available in https://packagist.org/packages/ishworkh/navigable-date.
With that is really easy to do what you're asking for here.
For e.g:
$format = 'Y-m-d H:i:s';
$Date = \NavigableDate\NavigableDateFacade::create('2017-02-24');
var_dump($Date->format($format));
$resetTime = true;
$resetDays = true;
$NextMonth = $Date->nextMonth($resetTime, $resetDays);
var_dump($NextMonth->format($format));
$DayUntilFirstOfNextMonth = $NextMonth->getDifference($Date);
var_dump('Days left:' . $DayUntilFirstOfNextMonth->format('%d'));
gives you ouput:
string(19) "2017-02-24 00:00:00"
string(19) "2017-03-01 00:00:00"
string(11) "Days left:5"
Note: Additionally this library let you navigate through dates by day(s), week(s), year(s) forward or backward. For more information look into its README.
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
To get the first day of next month a clean solution:
<?php
$date = new DateTimeInmutable('now');
$date->modify('first day of next month');//here the magic occurs
echo $date->format('Y-m-d') . '\n';
Since you just want to calculate it I suggest using DateTimeInmutable class.
using the class DateTime and $date->modify('first day of next month'); will modify your original date value.
$month = date('m')+1;
if ($month<10) {
$month = '0'.$month;
}
echo date('Y-').$month.'-01';
Simplest way to achieve this. You can echo or store into variable.
I came up with this for my needs:
if(date('m') == 12) { $next_month = 1; } else { $next_month = date('m')+1; }
if($next_month == 1) { $year_start = date('Y')+1; } else { $year_start = date('Y'); }
$date_start_of_next_month = $year_start . '-' . $next_month . '-01 00:00:00';
if($next_month == 12) { $month_after = 1; } else { $month_after = $next_month+1; }
if($month_after == 1) { $year_end = date('Y')+1; } else { $year_end = date('Y'); }
$date_start_of_month_after_next = $year_end . '-' . $month_after . '-01 00:00:00';
Please note that instead of getting $date_end_of_next_month I chose to go with a $date_start_of_month_after_next date, it avoids the hassles with leap years and months containing different number of days.
You can simply use the >= comparaision sign for $date_start_of_next_month and the < one for $date_start_of_month_after_next.
If you prefer a timestamp format for the date, from there you will want to apply the strtotime() native function of PHP on these two variables.
You can use the php date method to find the current month and date, and then you would need to have a short list to find how many days in that month and subtract (leap year would require extra work).

Categories