Get last day of last week using datetime - php

I have tried the following code to get the last day of week in the next month:
$paymentMonth = "2017-07";
$wee = new \DateTime($paymentMonth);
$firstDate = clone $wee->modify(('Sunday' == $wee->format('l')) ? 'Monday last week' : 'Monday this week'); //Monday of last week of previous month
$lastDate = clone $wee->modify('+1 month')->modify(('Sunday' == $wee->format('l')) ? 'Sunday last week' : 'Sunday this week');
/**^^^^
* This works in most cases of months
* but for july 2017, I want the last day of the first week of next month.
*/
echo $firstDate->format('Y-m-d'); //Gives 26-june
echo $lastDate->format('Y-m-d'); //Gives 30-july in this case i want the 31 of july...
What is the cleanest way to get the last day of first week of next month using DateTime

Use format placeholder 'w' to obtain day of week of first of the month. Then subtract the relative number of the day you want to obtain (Sunday = 7, Saturday = 6, Friday = 5 and so on). If you want to obtain first Sunday of the month:
$paymentMonth = '2017-06-01';
$d = new DateTime($paymentMonth);
$w = $d->modify('+1 month')->format('w'); // * Returns 6 as 1st July 2017 is Saturday
$sun = (7-$w + 1)%7; // * First Sunday is 7-$w + 1 = 2
$lastDate = new DateTime($d->format('Y-m') . "-$sun");
Module %7 is required as on Sunday format('w') returns 0.
Don't rely on format('l') as result is environment dependent.

I found the solution, was pretty easy actualy :
$paymentMonth = '2017-07';
$fweek = new \DateTime($paymentMonth);
$firstDate = $fweek->modify(('Sunday' == $fweek->format('l')) ? 'Monday last week' : 'Monday this week'); //Monday of last week of previous month
$lweek = new \DateTime($paymentMonth);
$lastDate = $lweek->modify('+1 month')->modify(('Sunday' == $lweek->format('l')) ? 'Sunday last week' : 'Sunday this week'); //Sunday of first week of next month
echo $firstDate->format('Y-m-d') . ' - ' . $lastDate->format('Y-m-d');

Related

Getting the First Sunday in any Given Year in PHP [duplicate]

I need to use PHP DateTime to get the first day of the current year. I've tried:
$year = new DateTime('first day of this year');
var_dump($year);
But this seems to be returning the first day of the current month: 2014-09-01 09:28:56
Why? How do I correctly get the first day of the current year?
Your relative date format 'first day of this year' is correct by returning the first day of the month because of the definition of first day of:
Sets the day of the first of the current month. This phrase is best
used together with a month name following it. (See PHP-doc)
To get the first day of the current year with the relative format you can use something like this:
'first day of January ' . date('Y')
Or use only text in the strtotime function:
date('Y-m-d', strtotime('first day of january this year'));
echo date('l',strtotime(date('Y-01-01')));
You can get the current date and then set day and month to 1:
$year = new DateTime();
$year->setDate($year->format('Y'), 1, 1);
Optionally, you can set the time to midnight:
$year->setTime(0, 0, 0);
If you want to get first day of current year just use this code
echo date("l", strtotime('first day of January '.date('Y') ));
Just wanted to record some nuance with the answer by lorem monkey
The suggested method might cause issues with when using time zones.
scenario: consider current system time is 2018-01-01 00:20:00 UTC and system default time zone is set to UTC.
date('Y') will give you 2018
if you are doing something like:
$startDate = new DateTime('first day of january '.date('Y'), new DateTimeZone('America/New_York'));
This will compute to 'first day of january 2018' but you actually needed the first date of your current year in America/New_York, which is still 2017.
Stop dropping the ball man, its not new year yet!
So it is better to just do
$startDate = new DateTime('first day of january', new DateTimeZone('America/New_York'));
And then do the modifications as needed by using the DateTime::modify() function.
Relative date formats are fun.
My scenario: I wanted to get the bounds of this year as in 2018-01-01 00:00:00 to 2018-12-31 23:59:59
This can be achieved in two ways with relative date formats.
one way is to use the DateTime::modify() function on the object.
$startDate = (new DateTime('now', new DateTimeZone("America/New_York")));
$endDate = (new DateTime('now', new DateTimeZone("America/New_York")));
$startDate->modify("january")
->modify("first day of this month")
->modify("midnight");
$endDate->modify("next year")
->modify("january")
->modify("first day of this month")
->modify("midnight")->modify("-1 second");
var_dump([$startDate, $endDate]);
Try out here: https://www.tehplayground.com/Qk3SkcrCDkNJoLK2
Another way to do this is to separate the relative strings with a comma like so:
$startDate = (new DateTime('first day of january', new DateTimeZone("America/New_York")));
$endDate = (new DateTime('next year, first day of january, -1 second', new DateTimeZone("America/New_York")));
var_dump([$startDate, $endDate]);
Try out here: https://www.tehplayground.com/hyCqXLRBlhJbCyks
Basically date('Y') returns the value of current year. and the first day of each year starts like 2000-01-01.
So this will help you to get exact output.
$firstdate = date( 'Y' ) . '-01-01';
Take a look at this link -- http://davidhancock.co/2013/11/get-the-firstlast-day-of-a-week-month-quarter-or-year-in-php/
function firstDayOf($period, DateTime $date = null)
{
$period = strtolower($period);
$validPeriods = array('year', 'quarter', 'month', 'week');
if ( ! in_array($period, $validPeriods))
throw new InvalidArgumentException('Period must be one of: ' . implode(', ', $validPeriods));
$newDate = ($date === null) ? new DateTime() : clone $date;
switch ($period) {
case 'year':
$newDate->modify('first day of january ' . $newDate->format('Y'));
break;
case 'quarter':
$month = $newDate->format('n') ;
if ($month < 4) {
$newDate->modify('first day of january ' . $newDate->format('Y'));
} elseif ($month > 3 && $month < 7) {
$newDate->modify('first day of april ' . $newDate->format('Y'));
} elseif ($month > 6 && $month < 10) {
$newDate->modify('first day of july ' . $newDate->format('Y'));
} elseif ($month > 9) {
$newDate->modify('first day of october ' . $newDate->format('Y'));
}
break;
case 'month':
$newDate->modify('first day of this month');
break;
case 'week':
$newDate->modify(($newDate->format('w') === '0') ? 'monday last week' : 'monday this week');
break;
}
return $newDate;
}
in PHP 5.3.10 this works
$myDate = new \DateTime(date("Y")."-01-01");
echo $myDate->format("Y-m-d");
In PHP 5.4 and upper you can put all together
echo (new \DateTime(date("Y")."-01-01"))->format("Y-m-d")
As a commenter #Glavić said already
$year = new DateTime('first day of January');
is the solution.
To me it did make sense semantically that "this year" should return midnight of the first day of the year, but indeed it does not!
Following is the code snippet for getting first and last day of the year.
$firstDayOfYear = date('Y-01-01');
$lastDayOfYear = date('Y-12-t');
Try this:
$dt = date('m/d/Y',time());
echo 'First day : '. date("01/01/Y", strtotime($dt)).' - Last day : '. date("m/t/Y", strtotime($dt));
Getting first and last day of the current year using DateTime object.
$currentDate = new \DateTime("NOW");
$yearStartString = $currentDate->format("Y")."-01-01 00:00:00";
$yearEndString = $currentDate->format("Y")."-12-31 23:59:59";
$yearStartDate = \DateTime::createFromFormat("Y-m-d H:i:s", $yearStartString);
$yearEndDate = \DateTime::createFromFormat("Y-m-d H:i:s", $yearEndString);

How can I make date("W") start in Sunday and end on saturday? [duplicate]

I need to get week number in php where week should be calculated from sunday. By default its from monday. Please help me to find a way how to get week number considering sunday as starting day.
In php manual
ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0)
But I need to get week number of year, weeks starting on sunday.
thanks
Try this:
$week = intval(date('W'));
if (date('w') == 0) { // 0 = Sunday
$week++;
}
echo $week;
Not sure if the logic is right though;
The first solution is not correct on Jan 01, 2017 or any year that begins on a Sunday.
Try this:
$date = date('Y-m-d');
echo strftime("%U", strtotime($date ) );
To expand on silkfire answer and allow for it wrapping around years
if($date->format('w') == 0){
if(date('W',strtotime($date->format('Y')."-12-31"))==52 and $date->format('W') == 52){
$week = 1;
}
elseif(date('W',strtotime($date->format('Y')."-12-31"))==53 and $date->format('W') == 53){
$week = 1;
}
else{
$week++;
}
}
Try this one. to get sunday day must -1 day.
$date = "2015-05-25";
echo date("W", strtotime("-1 day",strtotime($date)));
You should try with strftime
$week_start = new DateTime();
$week = strftime("%U"); //this gets you the week number starting Sunday
$week_start->setISODate(2012,$week,0); //return the first day of the week with offset 0
echo $week_start -> format('d-M-Y'); //and just prints with formatting
I solved this like this:
function getWeekOfYear( DateTime $date ) {
$dayOfweek = intval( $date->format('w') );
if( $dayOfweek == 0 ) {
$date->add(new DateInterval('P1D'));
}
$weekOfYear = intval( $date->format('W') );
return $weekOfYear;
}
I know this topic is old, but this is a shorter way to do it with elvis operator and "+7 day" expression for strtotime():
$week=date("W",strtotime(date("w")==1?"+7 day":"+0 day"));
if $date("w") returns true means today is a day between tuesday and sunday (1-6), so, we can return today week ('today').
if returns false, it means is monday (0), so, we should return the next day ('+1 week').
This way we don't need to care about last or first day of year or check if current year has 52 or 53 weeks.
Edited: the previous answer (and others in this topic) doesn't work for this year because januray 1st is monday, so, it needs to be 1 week ago (-1 week) excluding sunday (day 6).
date("W",strtotime(date("w")?'-7 day':'+0 day'));
I think a condition asking if januray 1st is monday could work, but I didn't test it yet, I will come back with an answer later
For a custom day you could use this:
$date = strtotime('2018-04-30'); // (it is monday)
if(date("w",strtotime(date('Y',$date).'-01-01'))==1){ // if first day of year is monday
$week = strtotime(date('w',$date)?"-7 day":"+0 day",$date); // and today is sunday, sub a week
$week = date("W",$week);
}else{ // if is not monday
$week = strtotime(date('w',$date)==1?"+7 day":"+0 day",$date); // and today is monday, add a week
$week = date("W",$week);
}
Building on #silkfire's answer:
$year = date('Y');
$week_no = date('W');
if (date('w') == 0) { // 0 = Sunday
$week_no++;
}
// We shifted the week but the week still starts on a Monday.
$weekStartDate = new DateTime();
$weekStartDate->setISODate($year,$week_no);
// Shift start date to Sunday
$weekStartDate->add(DateInterval::createFromDateString('-1 day'));
Tested in php 5.6 Debian 7
function getWeekNumber(\DateTime $_date)
{
$week = intval($_date->format('W'));
if(intval($_date->format('w')) == 0) {
$week = intval($_date->format('W')) == ( 52 + intval($_date->format('L')) ) ? 1 : $week + 1;
}
return $week;
}
I needed to ADD day instead of subtracting to get Alghi Fari's answer to work.
$date = "2022-11-13";
echo date("W", strtotime("+1 day",strtotime($date)));

strtotime() Get 7th day of -1 month

I have tried :
$firstOfMonth = "2015-01-01";
$last_month = date("Y-m-d", strtotime('first day of -1 month', strtotime($firstOfMonth)));
/* ^^^^^ This gives me 01 of last month */
/*** Tried 'seventh day of -1 month'
/* it gives 1970-01-01
*/
What I want is to get the 07 of last month.
uhm....the first day of a month is allways 01....so basically you only need year and month:
$firstOfMonth = "2015-01-01";
$last_month = date("Y-m-01",strtotime("-1 month",strtotime($firstOfMonth)));
Just like Mr.Manhattan said, you just need the year and month and to the seventh day you can leave it hard coded or in a variable:
date("Y-m-07",strtotime("-1 month"));
$fixedDay = '07';
echo date("Y-m-$fixedDay",strtotime("-1 month"));

How to check that day is last day of month in php?

My previous question: how-to-find-current-day-no-in-month-in-php
Now I face another problem. Suppose I know that this monday is the 4th monday of the current month. Now how to check that this monday is also the last monday of the current month?
exa:1
date: 27-01-2014
Using the code below, I get the name and number of a day:
day: monday
day no :4th
This is the 4th monday of january and it is also the last monday of january. How to check that?
exa:2
date: 20-01-2014
day: monday
day no :3rd
Here this monday is 3rd monday of january but not last monday of january.
So, in short, when I got a day number then how to check whether that the day number is last or not?
code:
$t=date('d-m-Y');
$dayName = strtolower(date("D",strtotime($t)));
$dayNum = strtolower(date("d",strtotime($t)));
$dayno = floor(($dayNum - 1) / 7) + 1
The quickest way to check if today is the last of the month I would suggest the following
if(date('t') == date('d')){
echo 'Last day of the month.';
}
This compares the current day with the number of days of the current month.
Just add 7 days (you still have a monday) to the date you have, and check if it's in the same month.
The complete solution is as follow. Thanks to #Oliver M Grech and #Nanne.
$t=date('d-m-Y');
$day = strtolower(date("D",strtotime($t)));
$month = strtolower(date("m",strtotime($t)));
$dayNum = strtolower(date("d",strtotime($t)));
$weekno = floor(($dayNum - 1) / 7) + 1;
if($weekno=="4" or $weekno=="5")
{
$Date = date("d-m-Y");
$new_month = date('m', strtotime($Date. ' + 7 days'));
if($new_month != $month)
{
echo "This ".$day." is last day of month." ;
}
}

Get the first week day in a given week number in PHP

How can I get the first week day in a given week number?
I'm making a function in PHP for a calendar app.
The idea: When I click on a link that basically uses strtotime with +1 month it only jumps to that same day of course. I need to get the week numbers correct.
Example: When I use the menu to move from August to September, it shouldn't select the same date I was in in August, but the first day of the first week number in September (Monday, 2th of September, week number 36).
And from September to October: Week number 40, Tuesday the 1th of October.
I found a function that exactly like you want it. This is setISODate
$date = new DateTime();
$date->setISODate(2013, 35, 1);
echo $date->format('Y-m-d');
You can change Y-m-d date format as you want
Output
2013-08-26 // This week number and monday
Usage
setISODate(year, week, day)
Try this code
<?php
$week = 3;
$year = 2009;
$timestamp = mktime( 0, 0, 0, 1, 1, $year ) + ( $week * 7 * 24 * 60 * 60 );
$timestamp_for_monday = $timestamp - 86400 * ( date( 'N', $timestamp ) - 1 );
$date_for_monday = date( 'Y-m-d', $timestamp_for_monday );
?>
Like every1 already said, ISO weeks start with monday. Quote from http://en.wikipedia.org/wiki/ISO_week_date : Weeks start with Monday.
If I understand your problem correctly, you need first-next-date in next month if selected week is in 2 different months?
function getFirstWeekDay($year, $week) {
$dt = (new DateTime)->setISODate($year, $week, 1);
$dtC = clone $dt;
for ($N = $dt->format('N'); $N < 7; $N++) {
$dtC->modify('+1 day');
if ($dt->format('m') !== $dtC->format('m')) {
return $dtC;
}
}
return $dt;
}
echo getFirstWeekDay(2013, 40)->format('W\t\h \w\e\e\k \i\s Y-m-d');
# 40th week is 2013-10-01
echo getFirstWeekDay(2013, 1)->format('W\t\h \w\e\e\k \i\s Y-m-d');
# 1th week is 2013-01-01

Categories