PHP - Date function - finding the previous week - php

In my application a week is defined from Monday 12:00:00 AM to Sunday 11:59:59 PM
Whenever a user visits my site - I need to find the previous weeks date range and show him results based on that. It sounds simple but I'm lost.
To give you scenarios -
- March 1st Monday 12:00:00 AM to March 7th Sunday 12:59:59 PM is the week.
Now when a user visits the website on 8th March or 10th March or 12th March - based on the current date I should be able to get the previous week date range ie start date March 1st and end date March 7th.
But if the user visits the site say on 16th March - the date range I would need is March 8th to March 15th.
How can I do this in PHP.
Thanks

You could try doing it with timestamps, but that gets messy with timezone changes (for example, CET -> CEST). I'd use the DateTime class:
$d = new DateTime();
$weekday = $d->format('w');
$diff = 7 + ($weekday == 0 ? 6 : $weekday - 1); // Monday=0, Sunday=6
$d->modify("-$diff day");
echo $d->format('Y-m-d') . ' - ';
$d->modify('+6 day');
echo $d->format('Y-m-d');

The strtotime function is very handy here:
$mondayStr = "last monday";
if (date('N') !== '1') { // it's not Monday today
$mondayStr .= " last week";
}
$monday = strtotime($mondayStr);
echo date('r', $monday); // Mon, 22 Feb 2010 00:00:00 +1000
$sunday = strtotime('next monday', $monday) - 1;
echo date('r', $sunday); // Sun, 28 Feb 2010 23:59:59 +1000

function get_week_start($year, $month, $day)
{
$timestamp = mktime(0, 0, 0, $month, $day, $year);
return date('F j Y', $timestamp = mktime(0, 0, 0, $month, date('d', $timestamp)-date('w', $timestamp), $year));
}
You could perhaps add the next 6 days and you have it.

There is a user function for this in the PHP Documentation.

GMT version
$prev_monday_t = time() - (gmdate('N') + 6) * 86400;
$prev_sunday_t = time() - gmdate('N') * 86400;
echo gmdate('Y-m-d H:i:s', $prev_monday_t ).' '.gmdate('Y-m-d H:i:s', $prev_sunday_t );
Local version
$prev_monday_t = time() - (date('N') + 6) * 86400;
$prev_sunday_t = time() - date('N') * 86400;
echo date('Y-m-d H:i:s', $prev_monday_t ).' '.date('Y-m-d H:i:s', $prev_sunday_t );

Related

Display date that changes every 15th day of the month

I'm relatively new to php and is currently looking for a way to display a date that adds 1 month on current date and adds 2 months every 15th day of every month.
For example:
Current Date: January 13, 2022
Display Date: February 2022
on January 15, 2022 the date to be displayed is March 2022 (which will be the displayed until February 14, 2022)
on February 15, 2022 the date to be displayed is April 2022
<?php
$today = date("D");
$date = date("F Y", strtotime(" +1 months"));
if ($today >= "15") {
$d=strtotime("+2 Months");
echo date("F Y", $d);
} else {
echo $date;
}
?>
Thanks in advance for your help.
Your code is almost fine.
data("D") instead of returning 15 will return the day string of the week (mon, wed, etc) so when you compare date("D") with 15 you are comparing "mon" with 15.. (not right). You have to use "d" instead (lowercase d)
This is my version of your same code
if (date("d") >= 15) {
$show_date = date("F Y", strtotime("+2 Month"));
} else {
$show_date = date("F Y", strtotime("+1 Month"));
}
echo $show_date;
Or if you prefer 1 line solution:
echo date("F Y", strtotime("+" . (date("d") >= 15 ? 2 : 1) . " Month"));

PHP strtotime returns incorrect month [duplicate]

Current Date is 29th March 2017
When I subtract 2 months using PHP and I get January
$prevmonth = date('M', strtotime('-2 months'));
echo $prevmonth;
But when I subtract 1 month it gives March
$prevmonth = date('M', strtotime('-1 months'));
echo $prevmonth;
strtotime() uses 30 day months and there are only 28 in days in February (this year) so will not yield a valid date in February. You could use the current day d or j and subtract that which will always put you in the previous month (-29 days):
$prevmonth = date('M', strtotime('-' . date('d') . ' days'));
This will get December from January as well.
As covered in the comments, there's no 29th Feb.
29th Feb becomes 1st March.
You may be better to get the current month number, -1 from it, and then get the textual representation.
$prevMonth = date('n') - 1;
$prevMonthText = date('M', mktime(0, 0, 0, $prevMonth, 10));
Or, you could use DateTime if your PHP version allows (it should).
$prevMonth = date('n') - 1;
$dateObj = DateTime::createFromFormat('!m', $prevMonth);
$monthName = $dateObj->format('M'); // March
The only issue with this, that you might have spotted, is January will never return December. A quick ternary statement will catch that.
$prevMonth = ((date('n') - 1) < 1) ? 12 : date('n') - 1;

How to get previous year's date relative to week of year

How can I get the same day of the same ISO-8601 week number but in the previous year using php?
I am familiar with extracting this soft of information from a time stamp. Is there a built-in way for me to go from day of week, week of year and year to time stamp?
You can use the combination of both date and strtotime like so:
// get the timestamp
$ts = strtotime('today');
// get year, week number and day of week
list($year, $week, $dow) = explode('-', date('Y-W-N', $ts));
// use the "YYYY-WXX-ZZ" format
$format = ($year - 1) . "-W$week-$dow";
echo date('Y-m-d', strtotime($format)), PHP_EOL;
You can do this with strtotime:
$now = time(); // Mon, 12 Nov 2012
$targetYear = date('Y', $now) - 1; // 2011
$targetWeek = date('\\WW-N', $now); // W46-1
$lastYear = strtotime($targetYear . $targetWeek); // Mon, 14 Nov 2011
Try this one:
$date = "2012-11-13";
echo getLastYearWeek($date);
function getLastYearWeek($date)
{
$last_year = date("Y-m-d W N", strtotime("-52 Weeks ".$date));
return $last_year;
}
Or just,
$last_year = date("Y-m-d W N", strtotime("-52 Weeks ".$date));
Use this for reference.
I think you are looking for mktime. have a look here http://php.net/manual/en/function.mktime.php

last week, this week (php)

i am making some statistics, i want to select the time from (last week only) and this week.
for this week its easy:
$start = strtotime('this week');
$finish = time();
for last week
$start = strtotime('last week');
$finish = ??????
This?
$start = strtotime('2 weeks ago');
$finish = strtotime('last week');
Edit: change credit to #Dominic Barnes's comment.
If the question is for statistical PHP script. Then all of the answers and basically the question is wrong.
Last week in statistics = One before currently running week from Sunday to Monday
This week in statistics = Currently running week from Sunday to Monday
(or Monday to Sunday, depending on which calendar you are used to, but in PHP that's one week)
This means, its not from today minus 7 days. That is not last or this week. So the selected answer currently, is in correct and counts 7 days back. Granted, its Sunday, at the time of testing, so it shows correct. But by editing the now date, you can see the problem:
// Selected answer:
$start = strtotime('2 weeks ago');
$finish = strtotime('last week');
// But if today isn't Sunday, you can see the code is wrong:
echo date("d.m.Y", strtotime("1 week ago", strtotime('yesterday')));
// Output: 15.08.2015 00:00:00 - 17.08.2015 00:00:00
You have to set the start of the week and the end of the week. strtotime() can support more stuff, so you can most likely make this answer better and more neat. However you get the working code and a good example of the logic from...
My proposed solution:
$today = strtotime('today 00:00:00');
$this_week_start = strtotime('-1 week monday 00:00:00');
$this_week_end = strtotime('sunday 23:59:59');
$last_week_start = strtotime('-2 week monday 00:00:00');
$last_week_end = strtotime('-1 week sunday 23:59:59');
echo date('d.m.Y H:i:s', $today) . ' - Today for example purposes<br />';
echo date('d.m.Y H:i:s', $this_week_start) . ' - ' . date('d.m.Y H:i:s', $this_week_end) . ' - Currently running week period<br />';
echo date('d.m.Y H:i:s', $last_week_start) . ' - ' . date('d.m.Y H:i:s', $last_week_end) . ' - Last week period<br />';
Above currently produces:
30.08.2015 00:00:00 - Today for example purposes
24.08.2015 00:00:00 - 30.08.2015 23:59:59 - Currently running week period
17.08.2015 00:00:00 - 23.08.2015 23:59:59 - Last week period
Because for statistics, it has to be accurate and if the end would be 00:00:00, then that date wont be counted in. And if the date would be one day later at 00:00:00, then the date is not correct. There for, this solution is the correct way to do this, for statistical purposes at least.
Is that what you want?
$start = strtotime('last week');
$finish = strtotime('this week');
Dominic also points out that time() === strtotime('this week') (CodePad).
If searching for the last week for statistical purposes, starting on Monday, ending on Sunday:
$last_week_start = strtotime("monday last week");
$last_week_end = strtotime("monday this week - 1 second");
"this week" is important, otherwise, if this weeks monday is already in the past (e.g. if it is tuesday already), it will give you the monday of next' week.
As for the months/years, I used the classy mktime approach:
last month
$last_month_start = mktime(0, 0, 0, date('m')-1, 01);
$last_month_end = mktime(23, 59, 59, date('m'), 0);
last year
$last_year_start = mktime(0, 0, 0, 1, 1, date('Y')-1);
$last_year_end = mktime(23, 59, 59, 1, 0, date('Y'));
If you are looking for "Last Week" instead of Last 7 days
$start = strtotime('Last Week'); // Will give you last Monday
$finish = strtotime('Last Sunday'); // Will give you last Sunday

Get timestamps of current week

I have a DateTime of current day. I need to get two unix timestamps of beggining and ending of current week. How can I use dateperiod or dateinterval class?
$now = time();
$beginning_of_week = strtotime('last Monday', $now); // Gives you the time at the BEGINNING of the week
$end_of_week = strtotime('next Sunday', $now) + 86400; // Gives you the time at the END of the last day of the week
if (date('w', time()) == 1)
$beginning_of_week = strtotime('Today',time());
else
$beginning_of_week = strtotime('last Monday',time());
if (date('w', time()) == 7)
$end_of_week = strtotime('Today', time()) + 86400;
else
$end_of_week = strtotime('next Sunday', time()) + 86400;
public static function getDaysInWeek($timestamp)
{
$monday = idate('w', $timestamp) == 1 ? $timestamp : strtotime("last Monday", $timestamp);
$days = array();
for ($i = 0; $i < 7; ++$i)
{
$days[$i] = strtotime('+' . $i . ' days', $monday);
}
return $days;
}
The simplest way I can think of is this (I'm assuming the usual European week format, replace with other day names to your liking):
$when = new DateTimeImmutable('1974-08-21 22:30:00'); // Wednesday
echo $when->modify('monday this week')->format('r'), PHP_EOL;
echo $when->modify('monday next week -1 second')->format('r'), PHP_EOL;
Mon, 19 Aug 1974 00:00:00 +0200
Sun, 25 Aug 1974 23:59:59 +0200
I've used DateTimeImmutable for simplicity, you can also use regular DateTime and clone objects.
Edge cases (date is either Monday or Sunday) should work as expected:
echo $when->modify('wednesday this week')->format('r'), PHP_EOL;
echo $when->modify('wednesday this week +1 day -1 second')->format('r'), PHP_EOL;
Wed, 21 Aug 1974 00:00:00 +0200
Wed, 21 Aug 1974 23:59:59 +0200

Categories