Finding date range for current week, month and year - php

Suppose I have a date available with me:
2011-04-05 (i.e., 5th April, 2011)
I want to find date range for Current Week, Month and Year
Current Week: 3rd April to 9th April
Current Month: 1st April to 30 April
Current Year: 1st Jan to 31 Dec
I do understand that current year would be always 1st Jan to 31Dec, but what about current month and week, How can I find it?
Edit:
How can I find date, which is 10 days earlier or later from a given date.
Example:
Suppose today's date is 6th April, 2011
10 day's earlier: 28 March, 2011
10 day's later: 15 April, 2011
Any thoughts on this, guys?

function rangeMonth ($datestr) {
date_default_timezone_set (date_default_timezone_get());
$dt = strtotime ($datestr);
return array (
"start" => date ('Y-m-d', strtotime ('first day of this month', $dt)),
"end" => date ('Y-m-d', strtotime ('last day of this month', $dt))
);
}
function rangeWeek ($datestr) {
date_default_timezone_set (date_default_timezone_get());
$dt = strtotime ($datestr);
return array (
"start" => date ('N', $dt) == 1 ? date ('Y-m-d', $dt) : date ('Y-m-d', strtotime ('last monday', $dt)),
"end" => date('N', $dt) == 7 ? date ('Y-m-d', $dt) : date ('Y-m-d', strtotime ('next sunday', $dt))
);
}
print_r (rangeMonth('2011-4-5')); // format: YYYY-M-D
print_r (rangeWeek('2011-4-5'));
output for rangeMonth()
Array
(
[start] => 2011-04-01
[end] => 2011-04-30
)
output for rangeWeek()
Array
(
[start] => 2011-04-04
[end] => 2011-04-08
)
Notice: functions like getdate(), date(), etc. throw Warning if default time zone is not set in php.ini.

you can use strtotime
example :
date('d.m.Y',strtotime('last day of this month'))
date('d.m.Y',strtotime('last monday')) // for first day of this week

This solution is simple, and it takes in consideration when the current day is Monday or Sunday.
NOTE: Using strtotime('last monday') may work if the day is other than Monday, otherwise it will return the previous Monday. Because of that we should use strtotime('last monday', strtotime('tomorrow')) and it will work for any day of the current week =)
Solution:
$monday = strtotime('last monday', strtotime('tomorrow'));
$sunday = strtotime('+6 days', $monday);
echo "<P>". date('d-M-Y', $monday) . " to " . date('d-M-Y', $sunday) . "</P>";

The following code will give you the start and last date of a week:
$today = getdate();
print_r($today);
echo "<br/>";
$weekStartDate = $today['mday'] - $today['wday'];
$weekEndDate = $today['mday'] - $today['wday']+6;
echo "<br/>";
echo "<br/>";
echo "week start date:".$weekStartDate;
echo "<br/>";
echo "week end date:".$weekEndDate;
Hope it helps...

Check out the getdate function, there are a few examples of how to use it on the manual page I linked. I think it will return everything you're looking for,

Working example it properly handles the Monday issue
<?php
$monday = strtotime("last monday");
$monday = date('w', $monday)==date('w') ? $monday+7*86400 : $monday;
$sunday = strtotime(date("Y-m-d",$monday)." +6 days");
$this_week_sd = date("Y-m-d",$monday);
$this_week_ed = date("Y-m-d",$sunday);
echo "Current week range from $this_week_sd to $this_week_ed ";
?>

Today is Tuesday, August 27th 2019
This week is from Monday, August 26th 2019 to Sunday, September 1st 2019
php > $date = new DateTime('Sunday');
php > echo $date->format('Y-m-d H:i:s');
2019-09-01 00:00:00
php > $date = new DateTime('Tuesday');
php > echo $date->format('Y-m-d H:i:s');
2019-08-27 00:00:00
php > $date = new DateTime('Monday');
php > echo $date->format('Y-m-d H:i:s');
2019-09-02 00:00:00
php > $date = new DateTime('Monday this week');
php > echo $date->format('Y-m-d H:i:s');
2019-08-26 00:00:00

Related

Date plus one month php [duplicate]

This question already has answers here:
PHP: Adding months to a date, while not exceeding the last day of the month
(7 answers)
Closed 6 years ago.
I have a small problem with dates in PHP.
When I made 31 + 1 month of January
with this code
$newDate = date('Y-m-d', strtotime('31-01-2016'.' + 1 month'));
echo $newDate;
it gives me 2 March but I need given me 29 February,
I need to add 1 month and is not 30days.
ditto for all dates:
for example
01 january + 1 month => 1 february
29 january + 1 month => 29 february
30 january + 1 month => 29 february
31 january + 1 month => 29 february
Thank for your help
I think you are looking for this type of dates.
<?php
$date = date('2016-01-31');
$currentMonth = date("m",strtotime($date));
$nextMonth = date("m",strtotime($date."+1 month"));
if($currentMonth==$nextMonth-1 && (date("j",strtotime($date)) != date("t",strtotime($date)))){
$nextDate = date('Y-m-d',strtotime($date." +1 month"));
}else{
$nextDate = date('Y-m-d', strtotime("last day of next month",strtotime($date)));
}
echo "Next date would be : $nextDate";
?>
Check live demo : https://eval.in/610034
If date is 31-01-2016 then next date would be 29-02-2016
If date is 25-01-2016 then next date would be 25-02-2016
Simply try:
$date = new DateTime('2016-01-31');
$date->modify('last day of next month');
This of course only counts if you always go from the end of one moth to the end of the next one.
try this,
$date = "2016-01-29";
$date = date('Y-m-d', strtotime("last day of next month",strtotime($date)));
echo $date;
https://3v4l.org/Y9PpV
How about something like this:
date_default_timezone_set('UTC');
$current_month = (int) date('m');
$year = date('y');
$newDate = date('Y-m-d', strtotime('31-1-2016'.' + 1 month'));
if($current_month == 12)
{
$new_month=0;
$year++;
}
$d = new DateTime( $year.'-'.($current_month+1).'-01' );
echo $d->format( 'Y-m-t' )."\n";
Change $current_month / $year based on your needs......

Finding the date for 29th last month, two months ago, etc

I'm looking to find the date of the 29th of this month, the 29th of next month, the 29th of last month and so on...
I know you can use this kind of code to find days of the week:
$friday_last = date("d/m/Y", strtotime("last Friday"));
$friday_due = date("d/m/Y", strtotime("this Friday"));
Is there a similar way to find a certain day (29th) of each month or would I have to use a different code?
You need to use DateTime() as it makes working with dates much easier. You'll notice I start by going to the first day of each month. That's so this doesn't break when you get to the 29th-30th of each month as weird date things start to happen.
echo (new DateTime())->modify('first day of this month')->format("29/m/Y");
echo (new DateTime())->modify('first day of previous month')->format("29/m/Y");
echo (new DateTime())->modify('first day of next month')->format("29/m/Y");
Demo
echo (new DateTime())->modify('first day of this month')->modify('-2 months')->format("29/m/Y");
Demo
Using date() with strtotime() will gives you 29th from each month within this year:
<?php
for ($i = 1; $i <= 12; $i++) {
$d = "2016-" . $i . "-29";
echo "29th of Month $i is: " . date("l", strtotime($d)) . '<br>';
}
?>
Output:
29th of Month 1 is: Friday
29th of Month 2 is: Monday
29th of Month 3 is: Tuesday
29th of Month 4 is: Friday
29th of Month 5 is: Sunday
29th of Month 6 is: Wednesday
29th of Month 7 is: Friday
29th of Month 8 is: Monday
29th of Month 9 is: Thursday
29th of Month 10 is: Saturday
29th of Month 11 is: Tuesday
29th of Month 12 is: Thursday
To create an array with current and next 11 months 29th day (for previous months replace +1 month with -1 month. In this example I use +1 to explain february issue, that is not present in past february):
$baseDate = date_create()->modify( 'first day of this month' );
$dates = array();
for( $i = 0; $i<12; $i++ )
{
$newDate = clone $baseDate;
$dates[] = $newDate->modify( '+28 days' );
$baseDate->modify( '+1 month' );
}
The problem — as you can imagine — is with february:
foreach( $dates as $date )
{
echo $date->format( 'Y-m-d' ).PHP_EOL;
}
Will output:
2016-05-29
2016-06-29
2016-07-29
2016-08-29
2016-09-29
2016-10-29
2016-11-29
2016-12-29
2017-01-29
2017-03-01 <-----
2017-03-29
2017-04-29
If you want a result like “29th month's day OR last month's day” modify above for loop in this way:
for( $i = 0; $i<12; $i++ )
{
$newDate = clone $baseDate;
if( $newDate->modify( '+28 days' )->format( 'm' ) != $baseDate->format( 'm' ) )
{
$newDate->modify( 'last day of previous month' );
}
$dates[] = $newDate;
$baseDate->modify( '+1 month' );
}
Result:
2016-05-29
2016-06-29
2016-07-29
2016-08-29
2016-09-29
2016-10-29
2016-11-29
2016-12-29
2017-01-29
2017-02-28 <-----
2017-03-29
2017-04-29
I'm not sure when this started, but now you can do so by using just date() and strtotime(), like this:
$d = date("Y-m-d 00:00:00", strtotime('first day of 2 months ago'));
$l = date("Y-m-d 00:00:00", strtotime('last day of 2 months ago'));
print_r($d);
print_r($l);
Assuming today (2023-02-01) The above will display:
2022-12-01 00:00:00
2022-12-31 00:00:00
Sample:
https://onlinephp.io/c/db73f

start and end of the week by given date

Is there a short preset function to find the start (Monday) and end (Sunday) of the week by a given $date ?
I tried:
1)
date("Y-m-d", strtotime('sunday this week ' . $date));
date("Y-m-d", strtotime('monday this week ' . $date));
But this fails when $date is Sunday... it returns the Monday of Next week.
2) also this
date("Y-m-d", strtotime('last monday ' . $date));
date("Y-m-d", strtotime('next sunday ' . $date));
But again if $date is Monday or Sunday it gives the previous/next week.
I know it can be done with few condition .. but I m look for more out of the box solution.
You can use DateTime::format('N') to get the ISO-8601 day of the week (1 = Monday .. 7 = Sunday) and do some simple date arithmetic to get the Monday and the Sunday of the week that contains the specified date (I assume you want the week starting on Monday).
// Today (or any other day you like)
$today = new DateTime('now');
echo('Today: '.$today->format('Y-m-d (D)')."\n");
// Day of week (1 = Monday .. 7 = Sunday)
$dow = $today->format('N');
// Monday is ($dow-1) days in the past
$monday = clone $today;
$monday->sub(new DateInterval('P'.($dow-1).'D'));
echo('Monday: '.$monday->format('Y-m-d')."\n");
// Sunday is 6 days after Monday
$sunday = clone $monday;
$sunday->add(new DateInterval('P6D'));
echo('Sunday: '.$sunday->format('Y-m-d')."\n");

How to get timestamp of current month, first day of month, zero hour

I am trying to get the timestamp of the first day of the month at 00:00:00.
For example, the timestamp of Jan 01 2012 00:00:00
I'm doing this:
$test_month = time(); // Seconds
$test_month = date('M', $test_month); // This month
$test_month = strtotime($test_month); // Timestamp of this month
echo $test_month;
This is returning zero hour of the current day of the month, not the start of the month.
Any suggestions?
Try this:
echo date( 'F jS Y h:i:s A', strtotime( 'first day of ' . date( 'F Y')));
This will output:
June 1st 2012 12:00:00 AM
Try this
$time = strtotime(date('Y-m-01 00:00:00')); // == 1338534000
Which translates to:
$date = date('Y-m-d H:i:s', $time); // == 2012-06-01 00:00:00
Read the PHP manual on the date() and time() functions.
echo date("Y-m-d 00:00:00", strtotime("first day of this month"));
This outputs:
2017-05-01 00:00:00

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