php week interval from date ("W") - php

Hy, I have in database number of the week date ("W") and I want to display week interval like 28 Jan -> 3 Feb in this format, and I don't know if it's possible. Can you help?
Thanks!

Try this
$year = 2013;
$week_no = 6;
$week_start = new DateTime();
$week_start->setISODate($year,$week_no);
$week_end = clone $week_start;
$week_end = $week_end->add(new DateInterval("P1W"));
echo $week_start->format('d-M-Y') . " - ".$week_end->format('d-M-Y');

Transform your intervals into timestamps.
If its not the first day of the week get the first day of that week with strtotime "last sunday" (or monday) for the first date.
Do the same for the second date this time geting the last day of the week with "next saturday" (or sunday);
Get both dates W and make a mysql comparison between the weeks.

Related

how to get previous month date range in php

I want to get the previous months date range with PHP. I have tried below function to get last month's date range.
$last_month_start_date = date('Y-m-d',strtotime('first day of last month'));
$last_month_end_date = date('Y-m-d',strtotime('last day of last month'));
echo $last_month_start_date.' - '.$last_month_end_date;
Output: 2019-09-01 - 2019-09-30
but how can I get previous month's date range with PHP?
can anybody help me with this?
To get Last to Last Month: If current month is October then below output gives first and last date of August
$last_to_last_start_date = $last_month_start_date = date('Y-m-d',strtotime('first day of last month -1 month'));
// outout 2019-08-01
$last_to_last_end_date = $last_month_end_date = date('Y-m-d',strtotime('last day of last month -1 month'));
// outout 2019-08-31
echo $last_to_last_start_date .' - '.$last_to_last_end_date ;
//Output : 2019-08-01 - 2019-08-31
Create a date-time object that is two months behind, then use a modifier of first/last day of this month. The this month modifier works on the month of the object, so if the object's date is in August, it will look for the first and last days of August.
This means that you can provide any value for -2 months (like February, -1 month) and it will get the start and end-dates for that month.
$start = new DateTime("-2 months");
$end = clone $start;
$start->modify("first day of this month");
$end->modify("last day of this month");
echo $start->format("Y-m-d")." - ".$end->format("Y-m-d");
In October 2019, this outputs,
2019-08-01 - 2019-08-31
Live demo at https://3v4l.org/udGtE

Get first day date of the week on a given date PHP

I have a date 2015-12-16
i want to get the date of the first day's date for the current week of my date
here 2015-12-16 is in the week 51 of the year then i want to get the first day's date of the week 51 ( 2015-12-14 here)
how could i do it ?
thank you
EDIT: it must work when there are 53 weeks in the year (like in 2015 for example)
You can do the following:
$dateTime = new DateTime("2015-12-16");
$weekNo = $dateTime->format("W");
$newDate = new DateTime();
$newDate->setISODate($dateTime->format("Y"), $weekNo);
Example:
http://sandbox.onlinephpfunctions.com/code/281a1ac298bfee8be421e333e4b7e92c6bb44d65
Since the above is a bit off in some cases here's something more reliable:
$dateTime = new DateTime("2016-01-01");
$dateTime->sub(new DateInterval("P".($dateTime->format("w")-1)."D")); //Since the weekdays are 1-based.
Example:
http://sandbox.onlinephpfunctions.com/code/c5cb0f077fa77974d977ddbffa6bc0b61f9d7851
$date = new \DateTime('2015-12-16');
echo $date->modify('last sunday +1 day')->format('Y-m-d');
This gets start of this week if you count monday to sunday.
Try this:
date('Y-m-d', strtotime('This week', strtotime('2015-12-16')));

Add multiple of interval to date until date is in current year

suppose I have an initial date whose year was prior to that of the current year and I want to repeat the event every 7 days but only in the current year.
How would I find the first occurrence in the current year?
I realize I can do it with a loop like this:
$reOccurringEvent =new DateTime('2013-12-01');
$interval = new DateInterval('P7D');
while($reOccurringEvent->format('Y') < date('Y') ){
$reOccurringEvent->add($interval);
}
echo $reOccurringEvent->format('d m Y'); //05 01 2014
But it strikes me there should be a more efficient way to achieve this rather than repeatedly adding an interval to the date (it would happen many times if the initial date was some years ago).
I was hoping to be able to calculate the number of times the interval should be added and just do it a single time.
I was thinking something like:
$date = new DateTime();
$diff = $date->diff($reOccurringEvent)->days%7;
But obviously that doesn't work and I can't quite figure out the logic of how to do it.
More generically, the algorithm would be to find the number of intervals between the given date and the last day of last year. Then multiplying the interval by the number of intervals + 1 to get the first interval of the current year.
$date1="12/9/2013";
$ts1 = strtotime($date1);
$ts2 = strtotime("12/31/" . Date("Y")-1);
//get the number of seconds between the date and first of the year
$seconds_diff = $ts2 - $ts1;
echo "$seconds_diff <br>";
//get the number of days
$dayDiff=$seconds_diff/86400;
//how many intervals?
$intervalDays = "10";
//get the number of intervals from start date to last day of last year
$numIntervals = floor($dayDiff/$intervalDays);
echo $numIntervals."<br>";
//now the total intervals to get into the current year is one more interval, turn this into days
$totIntervals= ($numIntervals* $intervalDays)+$intervalDays;
//Date Time date in question
$theDt = new DateTime($date1);
//Add the intervals we calculated to the date in question, and we have the first date of the interval for the current year...
$theDt->add(new DateInterval('P' . $totIntervals. 'D'));
echo "The first date of the intreval is: " . $theDt->format('Y-m-d');
I think, if you are doing 7 day intervals, you can find out the Day of week of your initial date, and then get the first date of the current year with that day of week...
Find out day of week: How to find the day of week from a date using PHP?
Find out date with that day of week for this year: Getting first weekday in a month with strtotime
Putting it together:
$date=Date("2/8/2012");
//Get the day of week for the date in question
$dayOfWeek = date('l', strtotime($date));
echo "The day of week for the given date is: $dayOfWeek <br>";
//Get the current year
$thisYear = date("Y");
echo "This year: $thisYear <br>";
//Create a date with the first occurence of the day of week of the given date for the current year
$firstOccurenceThisYear = date("m/d/y", strtotime("January " .$thisYear ." " . $dayOfWeek));
echo "The first interval of the year is: $firstOccurenceThisYear";
/*
Output:
This year: 2014
The day of week for the given date is: Wednesday
The first interval of the year is: 01/01/14
*/
Here is a slightly modified version of #Dan's second answer which worked well for me.
Benchmarks shown below.
$date="1985-02-18";
$intervalDays = "5";
//original version
$benchMark = microtime(true);
$dt1 = new DateTime($date);
$interval = new DateInterval("P{$intervalDays}D");
while ($dt1->format('Y') < date('Y')) {
$dt1->add($interval);
}
echo $dt1->format('d m Y') . '<br>';
echo microtime(true)-$benchMark.'<br>';
//new version
$benchMark = microtime(true);
$dt1 = new DateTime($date);
$dt2 = new DateTime("12/31/" . ((int) Date("Y") - 1));
$dayDiff = $dt1->diff($dt2)->days;
$numIntervals = floor($dayDiff / $intervalDays);
$totIntervals = ($numIntervals * $intervalDays) + $intervalDays;
$dt1->add(new DateInterval('P' . $totIntervals . 'D'));
echo $dt1->format('d m Y').'<br>';
echo microtime(true)-$benchMark.'<br>';
exit;
output
02 01 2014
0.0145111083984
02 01 2014
0.000123977661133

Finding first and last day of the week (or month, quarter, or year) [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Grab current first and last day in week in php
I am trying to get the first and last day of the week, month, quarter, and year for a given day.
For instance, for day 2013-01-16, the first and last days would be:
Week - It would be 2013-01-13 and 2013-01-19 (assuming Sunday to Saturday)
Month - It would be 2013-01-01 and 2013-01-31
Quarter - It would be 2013-01-01 and 2013-03-31
Year - It would be 2013-01-01 and 2013-12-31
My purpose is to include them in a WHERE myDate BETWEEN 2013-01-13 AND 2013-01-19.
Both a standard MYSQL function solution (but not stored procedure, etc) or PHP solution is acceptable. Thank you
Solution for first and last day of given quarter.
$q=ceil($date->format("n")/3);
$months_start=array('January','April','July','October');
$months_end=array('March','June','September','December');
$m_start=$months_start[$q-1];
$m_end=$months_end[$q-1];
$modifier='first day of '.$m_start.' '.$date->format('Y');
$date->modify($modifier);
echo $modifier.': '.$date->format('Y-m-d').'<br>';
$modifier='last day of '.$m_end.' '.$date->format('Y');
$date->modify($modifier);
echo $modifier.': '.$date->format('Y-m-d').'<br>';
You can use strtotime:
$date = strtotime('2013-01-16');
// First/last day of week
$first = strtotime('last Sunday');
$last = strtotime('next Saturday');
Or PHP's native DateTime functionality:
$date = new DateTime('2013-01-16');
// First/last day of month
$first = $date->modify('first day of this month');
$last = $date->modify('last day of this month');
Getting the first/last day of a year might be a little bit more tricky:
// Get date
$date = new DateTime('2013-01-16');
// Format to get date
$year = $date->format('Y');
// Get first day of Jan and last day of Dec
$first = $date->modify("first day of January $year");
$last = $date->modify("last day of December $year");

How to get previous month and year relative to today, using strtotime and date?

I need to get previous month and year, relative to current date.
However, see following example.
// Today is 2011-03-30
echo date('Y-m-d', strtotime('last month'));
// Output:
2011-03-02
This behavior is understandable (to a certain point), due to different number of days in february and march, and code in example above is what I need, but works only 100% correctly for between 1st and 28th of each month.
So, how to get last month AND year (think of date("Y-m")) in the most elegant manner as possible, which works for every day of the year? Optimal solution will be based on strtotime argument parsing.
Update. To clarify requirements a bit.
I have a piece of code that gets some statistics of last couple of months, but I first show stats from last month, and then load other months when needed. That's intended purpose. So, during THIS month, I want to find out which month-year should I pull in order to load PREVIOUS month stats.
I also have a code that is timezone-aware (not really important right now), and that accepts strtotime-compatible string as input (to initialize internal date), and then allows date/time to be adjusted, also using strtotime-compatible strings.
I know it can be done with few conditionals and basic math, but that's really messy, compared to this, for example (if it worked correctly, of course):
echo tz::date('last month')->format('Y-d')
So, I ONLY need previous month and year, in a strtotime-compatible fashion.
Answer (thanks, #dnagirl):
// Today is 2011-03-30
echo date('Y-m-d', strtotime('first day of last month')); // Output: 2011-02-01
Have a look at the DateTime class. It should do the calculations correctly and the date formats are compatible with strttotime. Something like:
$datestring='2011-03-30 first day of last month';
$dt=date_create($datestring);
echo $dt->format('Y-m'); //2011-02
if the day itself doesn't matter do this:
echo date('Y-m-d', strtotime(date('Y-m')." -1 month"));
I found an answer as I had the same issue today which is a 31st. It's not a bug in php as some would suggest, but is the expected functionality (in some since). According to this post what strtotime actually does is set the month back by one and does not modify the number of days. So in the event of today, May 31st, it's looking for April-31st which is an invalid date. So it then takes April 30 an then adds 1 day past it and yields May 1st.
In your example 2011-03-30, it would go back one month to February 30th, which is invalid since February only has 28 days. It then takes difference of those days (30-28 = 2) and then moves two days past February 28th which is March 2nd.
As others have pointed out, the best way to get "last month" is to add in either "first day of" or "last day of" using either strtotime or the DateTime object:
// Today being 2012-05-31
//All the following return 2012-04-30
echo date('Y-m-d', strtotime("last day of -1 month"));
echo date('Y-m-d', strtotime("last day of last month"));
echo date_create("last day of -1 month")->format('Y-m-d');
// All the following return 2012-04-01
echo date('Y-m-d', strtotime("first day of -1 month"));
echo date('Y-m-d', strtotime("first day of last month"));
echo date_create("first day of -1 month")->format('Y-m-d');
So using these it's possible to create a date range if your making a query etc.
If you want the previous year and month relative to a specific date and have DateTime available then you can do this:
$d = new \DateTimeImmutable('2013-01-01', new \DateTimeZone('UTC'));
$firstDay = $d->modify('first day of previous month');
$year = $firstDay->format('Y'); //2012
$month = $firstDay->format('m'); //12
date('Y-m', strtotime('first day of last month'));
strtotime have second timestamp parameter that make the first parameter relative to second parameter. So you can do this:
date('Y-m', strtotime('-1 month', time()))
if i understand the question correctly you just want last month and the year it is in:
<?php
$month = date('m');
$year = date('Y');
$last_month = $month-1%12;
echo ($last_month==0?($year-1):$year)."-".($last_month==0?'12':$last_month);
?>
Here is the example: http://codepad.org/c99nVKG8
ehh, its not a bug as one person mentioned. that is the expected behavior as the number of days in a month is often different. The easiest way to get the previous month using strtotime would probably be to use -1 month from the first of this month.
$date_string = date('Y-m', strtotime('-1 month', strtotime(date('Y-m-01'))));
I think you've found a bug in the strtotime function. Whenever I have to work around this, I always find myself doing math on the month/year values. Try something like this:
$LastMonth = (date('n') - 1) % 12;
$Year = date('Y') - !$LastMonth;
date("m-Y", strtotime("-1 months"));
would solve this
Perhaps slightly more long winded than you want, but i've used more code than maybe nescessary in order for it to be more readable.
That said, it comes out with the same result as you are getting - what is it you want/expect it to come out with?
//Today is whenever I want it to be.
$today = mktime(0,0,0,3,31,2011);
$hour = date("H",$today);
$minute = date("i",$today);
$second = date("s",$today);
$month = date("m",$today);
$day = date("d",$today);
$year = date("Y",$today);
echo "Today: ".date('Y-m-d', $today)."<br/>";
echo "Recalulated: ".date("Y-m-d",mktime($hour,$minute,$second,$month-1,$day,$year));
If you just want the month and year, then just set the day to be '01' rather than taking 'todays' day:
$day = 1;
That should give you what you need. You can just set the hour, minute and second to zero as well as you aren't interested in using those.
date("Y-m",mktime(0,0,0,$month-1,1,$year);
Cuts it down quite a bit ;-)
This is because the previous month has less days than the current month. I've fixed this by first checking if the previous month has less days that the current and changing the calculation based on it.
If it has less days get the last day of -1 month else get the current day -1 month:
if (date('d') > date('d', strtotime('last day of -1 month')))
{
$first_end = date('Y-m-d', strtotime('last day of -1 month'));
}
else
{
$first_end = date('Y-m-d', strtotime('-1 month'));
}
If a DateTime solution is acceptable this snippet returns the year of last month and month of last month avoiding the possible trap when you run this in January.
function fn_LastMonthYearNumber()
{
$now = new DateTime();
$lastMonth = $now->sub(new DateInterval('P1M'));
$lm= $lastMonth->format('m');
$ly= $lastMonth->format('Y');
return array($lm,$ly);
}
//return timestamp, use to format month, year as per requirement
function getMonthYear($beforeMonth = '') {
if($beforeMonth !="" && $beforeMonth >= 1) {
$date = date('Y')."-".date('m')."-15";
$timestamp_before = strtotime( $date . ' -'.$beforeMonth.' month' );
return $timestamp_before;
} else {
$time= time();
return $time;
}
}
//call function
$month_year = date("Y-m",getMonthYear(1));// last month before current month
$month_year = date("Y-m",getMonthYear(2)); // second last month before current month
function getOnemonthBefore($date){
$day = intval(date("t", strtotime("$date")));//get the last day of the month
$month_date = date("y-m-d",strtotime("$date -$day days"));//get the day 1 month before
return $month_date;
}
The resulting date is dependent to the number of days the input month is consist of. If input month is february (28 days), 28 days before february 5 is january 8. If input is may 17, 31 days before is april 16. Likewise, if input is may 31, resulting date will be april 30.
NOTE: the input takes complete date ('y-m-d') and outputs ('y-m-d') you can modify this code to suit your needs.

Categories