reduce month in timestamp php - php

I need a list which iterates through the months and always shows the last days like this
2015-04-30
2015-03-31
2015-02-28
...
My idea was to do this with the strtotime method, where '1430344800' is the timestep according to 2015-04-30
$time_temp = 1430344800;
echo date('Y-m-t',$time_temp)."<br>";
$time_temp = strtotime("-1 month",$time_temp);
echo date('Y-m-t',$time_temp)."<br>";
$time_temp = strtotime("-1 month",$time_temp);
echo date('Y-m-t',$time_temp)."<br>";
but I just get
2015-04-30
2015-03-31
2015-03-31
replacing 'Y-m-t' by 'Y-m-d' gives
2015-04-30
2015-03-30
2015-03-02
Why is it not reducing the month properly and how can I accomplish it?

$lastDayOfMonth = time(); // depending on what you're trying to do, this could change.
// For example, it could be = strtotime("+1 month");
for( $i = 0; $i < $numberOfMonthsToShow; $i++ ){
$lastDayOfMonth = strtotime("last day of previous month", $lastDayOfMonth);
echo date('Y-n-j', $lastDayOfMonth).'<br />';
}

Related

strtotime('-1 month') returning wrong date if month have 31 days

I'm trying make a function to return the exact date of previous months.
That is a example of my code:
// Dates in TimeStamp
$ts_now = strtotime('now');
$ts_month1 = strtotime("-1 month", $ts_now);
$ts_month2 = strtotime("-2 month", $ts_now);
$ts_month3 = strtotime("-3 month", $ts_now);
// Dates Formated
$date_now = date('Y-m-d', $ts_now);
$date_month1 = date('Y-m-d', $ts_month1);
$date_month2 = date('Y-m-d', $ts_month2);
$date_month3 = date('Y-m-d', $ts_month3);
//Output
echo $date_now; //2020-04-30
echo $date_month1; //2020-03-30
echo $date_month2; //2020-03-01
echo $date_month3; //2020-01-30
The problem is in $date_month2 that represents February, the output is 2020-03-01 instead 2020-02-29 and I suppose that problem will happen in months who have 30 days when present date have 31 days.
What is the best way to resolve that?
As you can see working with the end of the month can be problematic because of how PHP works with dates. Your best bet is to go back to the beginning of the month, do your date math (i.e. go backwards in time), and then go to the date you want. That way you can check to see if the current day is greater than the number of days in month. If so, use the last day of the month instead.
function getMonthsAgo(int $n): string {
$date = new DateTime();
$day = $date->format('j');
$date->modify('first day of this month')->modify('-' . $n . ' months');
if ($day > $date->format('t')) {
$day = $date->format('t');
}
$date->setDate($date->format('Y'), $date->format('m'), $day);
return $date->format('Y-m-d');
}
// Dates Formated
$date_now = date('Y-m-d');
$date_month1 = getMonthsAgo(1);
$date_month2 = getMonthsAgo(2);
$date_month3 = getMonthsAgo(3);
//Output
echo $date_now;
echo $date_month1;
echo $date_month2;
echo $date_month3;
Output:
2020-04-30
2020-03-30
2020-02-29
2020-01-30

Find Dates Before Specified Date and Insert Them Using PHP & SQL

I have a date outputted from the database:
$deadline = $row['DEADLINE'];
When I print $deadline it returns: 2015-05-03 18:00:00
Now I want a way to find each day 24 hours before up until todays date and then use each of those values to insert in a new table in the database.
So in this case I want:
2015-05-03 18:00:00
2015-05-02 18:00:00
2015-05-01 18:00:00
2015-04-30 18:00:00
2015-04-29 18:00:00
To be inserted into the database 5 new rows. So I know I need todays date:
$now = date("Y-m-d H:i:s");
Then I have the date of the deadline:
$deadline = $row['DEADLINE'];
I can then find the difference in days:
$dateDiff = ($deadline - $now)/(24*60*60);
This gives me a figure (in this case it will be 5). Then could I use this figure to display the date and time for 5 days prior?
Not sure how I would insert them all though. Your help would be appreciated.
Use DateTime object, really easiest way :
PHP :
$now = new datetime();
$sub = new datetime();
for($i=0;$i<5;$i++)
{
$sub->sub(new DateInterval('P1D'));
echo $sub->format('Y-m-d H:i:s').'<br />';
echo $sub->diff($now)->format('%a days').'<br />';
}
OUTPUT :
2015-04-29 14:18:09
1 days
2015-04-28 14:18:09
2 days
2015-04-27 14:18:09
3 days
2015-04-26 14:18:09
4 days
2015-04-25 14:18:09
5 days
This isent perfect, but it will probably get you started
Try Using Datetime http://php.net/manual/en/class.datetime.php
Or Carbon/Carbon Package: https://github.com/briannesbitt/Carbon
$datetime = new DateTime("2015-04-03 18:00:00");
$now = new DateTime('NOW');
$difference = $datetime->diff($now);
echo '<pre>';
for($i = 1; $i <= $difference->days; $i++)
{
if($difference->invert){
var_dump (
$temp = $datetime
->modify('-1 day')
->format('Y-m-d H:i:s')
);
}else{
var_dump (
$temp = $datetime
->modify('+1 day')
->format('Y-m-d H:i:s')
);
}
}

how do i get 5 dates of current week with php or jquery?

i have this and yesterday it worked fine, but not today.
$current_dayname = date("l");
$datemon = date("m-d-Y",strtotime('monday this week'));
$datetue = date("m-d-Y",strtotime("tuesday this week"));
$datewed = date("m-d-Y",strtotime("wednesday this week"));
$datethu = date("m-d-Y",strtotime("thursday this week"));
$datefri = date("m-d-Y",strtotime("friday this week"));
yesterday, $datemon through $datefri would get the values of 1-20-2014 through 1-24-2014, but today only tuesday through friday is working and monday is getting the date for next monday, not yesterday.
how can i get the dates of the 5 weekdays of the current week? so if it's wednesday for example, the 5 variables should be 2 for 2 days past, 1 for current day, and 2 for future days. know what i mean?
i'm going to guess that someone will ask if week starts with monday or sunday. doesn't really matter as long as script works, but the week starting on a monday is preferable.
An easier way to get those dates might be something like this:
$today = time();
$wday = date('w', $today);
$datemon = date('m-d-Y', $today - ($wday - 1)*86400);
$datetue = date('m-d-Y', $today - ($wday - 2)*86400);
$datewed = date('m-d-Y', $today - ($wday - 3)*86400);
$datethu = date('m-d-Y', $today - ($wday - 4)*86400);
$datefri = date('m-d-Y', $today - ($wday - 5)*86400);
I would also recommend using an array instead of 5 different variables, but that's a separate concern.
Simple DateTime::setISODate() example:
$dt = new DateTime();
$dates = [];
for ($d = 1; $d <= 5; $d++) {
$dt->setISODate($dt->format('o'), $dt->format('W'), $d);
$dates[$dt->format('D')] = $dt->format('m-d-Y');
}
print_r($dates);
will output:
Array
(
[Mon] => 01-20-2014
[Tue] => 01-21-2014
[Wed] => 01-22-2014
[Thu] => 01-23-2014
[Fri] => 01-24-2014
)
demo

Finding Last Day of Previous Month in PHP

I'm a little unsure why this is not able to find the last day of the previous month. Every steps seems to be working correctly, except when the final date is created.
<?php
$currentMonth = date('n');
$currentYear = date('Y');
if($currentMonth == 1) {
$lastMonth = 12;
$lastYear = $currentYear - 1;
}
else {
$lastMonth = $currentMonth -1;
$lastYear = $currentYear;
}
if($lastMonth < 10) {
$lastMonth = '0' . $lastMonth;
}
$lastDayOfMonth = date('t', $lastMonth);
$lastDateOfPreviousMonth = $lastYear . '-' . $lastMonth . '-' . $lastDayOfMonth;
$newLastDateOfMonth = date('F j, Y', strtotime($lastDateOfPreviousMonth));
?>
$lastDateOfPreviousMonth is returning 2012-09-30 as expected; however, after trying to convert it to September 30, 2012 - $newLastDateOfMonth is returning October 1, 2012. Where do I seem to be going wrong?
EDIT: If using date("t/m/Y", strtotime("last month")); or date('Y-m-d', strtotime('last day of previous month')); will either of these still be viable given 2013-01-01, i.e. will they account for the change in year?
echo date('Y-m-d', strtotime('last day of previous month'));
//2012-09-30
or
$date = new DateTime();
$date->modify("last day of previous month");
echo $date->format("Y-m-d");
Later edit: php.net documentation - relative formats for strtotime(), DateTime and date_create()
There is a php function for this.
echo date("t/m/Y", strtotime("last month"));
First day of this month, minus 1 second.
echo date('Y-m-d',strtotime('-1 second',strtotime(date('m').'/01/'.date('Y'))));
Example here.
please try with below answer.
code:
echo date("t/m/Y", strtotime(date('Y-m')." -1 month"));
You will get last day of previous 12 months.
Example:
<?php
for ($i = 1; $i <= 12; $i++) {
$months[] = date("t/m/Y l", strtotime(date('Y-m')." -$i months"));
}
print_r($months);
?>
Output:
Array
(
[0] => 30/11/2018 Monday
[1] => 31/10/2018 Friday
[2] => 30/09/2018 Wednesday
[3] => 31/08/2018 Sunday
[4] => 31/07/2018 Thursday
[5] => 30/06/2018 Tuesday
[6] => 31/05/2018 Saturday
[7] => 30/04/2018 Thursday
[8] => 31/03/2018 Monday
[9] => 28/02/2018 Monday
[10] => 31/01/2018 Friday
[11] => 31/12/2017 Tuesday
)
You can use strtotime()'s zero handling functionality to achieve this also:
# Day Before
echo date('Y-m-d', strtotime('2016-03-00')); // 2016-02-29
# Year can be handled too
echo date('Y-m-d', strtotime('2016-01-00')); // 2015-12-31
# Month Before
echo date('Y-m-d', strtotime('2016-00-01')); // 2015-12-01
# Month AND Day
echo date('Y-m-d', strtotime('2016-00-00')); // 2015-11-30
Makes sense if you think of 00 as 'one less than the first (01)'.
So to achieve the objective of this question, 'last day of previous month' is a simple case of
date('your_format', strtotime('YYYY-ThisMonth-00'));
# So:
date('Y-m-d', strtotime('2016-11-00')); // 2016-10-31

php - find date for same day of week for last year

So, in PHP i'm trying to return a date value for last year based on the same day of week.
EX: (Monday) 2011-12-19 inputted should return (Monday) 2010-12-20.
I was just doing it simply by -364 but then that was failing on leap years. I came across another function :
$newDate = $_POST['date'];
$newDate = strtotime($newDate);
$oldDate = strtotime('-1 year',$newDate);
$newDayOfWeek = date('w',$oldDate);
$oldDayOfWeek = date('w',$newDate);
$dayDiff = $oldDayOfWeek-$newDayOfWeek;
$oldDate = strtotime("$dayDiff days",$oldDate);
echo 'LAST YEAR DAY OF WEEK DATE = ' . date('Ymd', $oldDate);
however, that is failing when you try to input a Sunday date, as it does a 0 (sunday) minus 6 (saturday of last year date), and returns with a value T-6. IE inputting 2011-12-25 gets you 2010-12-19 instead of 2011-12-26.
I'm kind of stumped to find a good solution in php that will work for leap years and obviously all days of the week.
Any suggestions?
Thanks!
How about this, using PHP's DateTime functionality:
$date = new DateTime('2011-12-25'); // make a new DateTime instance with the starting date
$day = $date->format('l'); // get the name of the day we want
$date->sub(new DateInterval('P1Y')); // go back a year
$date->modify('next ' . $day); // from this point, go to the next $day
echo $date->format('Ymd'), "\n"; // ouput the date
$newDate = '2011-12-19';
date_default_timezone_set('UTC');
$newDate = strtotime($newDate);
$oldDate = strtotime('last year', $newDate);
$oldDate = strtotime(date('l', $newDate), $oldDate);
$dateFormat = 'Y-m-d l w W';
echo "This date: ", date($dateFormat, $newDate), "\n";
echo "Old date : ", date($dateFormat, $oldDate);
That gives:
This date: 2011-12-19 Monday 1 51
Old date : 2010-12-20 Monday 1 51
Use strtotime() to get a date, for the same week last year.
Use the format {$year}-W{$week}-{$weekday}, like this:
echo date("Y-m-d", strtotime("2010-W12-1"));
And you can do that for as long back you wan't:
<?php
for($i = 2011; $i > 2000; $i--)
echo date("Y-m-d", strtotime($i."-W12-1"));
?>
Make it easier :)
echo date('Y-m-d (l, W)').<br/>;
echo date('Y-m-d (l, W)', strtotime("-52 week"));
Edit: I forgot to write output: :)
2015-05-06 (Wednesday, 19)
2014-05-07 (Wednesday, 19)
<?php
$date = "2020-01-11";
$newdate = date("Y-m-d",strtotime ( '-1 year' , strtotime ( $date ) )) ;
echo $newdate;
?>
ref https://www.nicesnippets.com/blog/how-to-get-previous-year-from-date-in-php

Categories