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
Related
This give me every monday date in date range.
Question: How to get every monday and friday of week?
$start_date = date('Y-m-d');
$end_date = date('Y-m-d', strtotime($start_date . ' + 1 MONTH'));
for(
$i = strtotime('Monday', strtotime($start_date));
$i <= strtotime($end_date);
$i = strtotime('+1 WEEK', $i)
) {
echo date('Y-m-d', $i). '<br>';
}
My Update:
$my_dates = [];
for(
$i = strtotime($start_date);
$i <= strtotime($end_date);
$i = strtotime('+1 DAY', $i)
) {
if(in_array(date('N', $i), array(1, 5))) {
$my_dates[] = date('Y-m-d', $i);
}
}
var_dump($my_dates);
Have a look at library called When, it's "Date / Calendar recursion library for PHP 5.3+".
Let's say MF schedule for next month:
$now = new DateTime('NOW');
$till = clone $now;
$till->modify('+1 month');
$r = new When();
$r->startDate($now)
->freq("weekly")
->until($till)
->byday(array('MO', 'FR'))
->generateOccurrences();
$occurrences = $r->occurrences;
If I'm not wrong than you can simply use for loop like as
$start = "2015-09-01";
$end = date('Y-m-d', strtotime("$start +1 months"));
$period = floor((strtotime($end) - strtotime($start))/(24*60*60));
for($i = 0; $i < $period; $i++){
if(in_array(date('l',strtotime("$start +$i day")),["Monday","Friday"]))
echo date('l d M, Y',strtotime("$start +$i day"))."\n";
}
Output:
Friday 04 Sep, 2015
Monday 07 Sep, 2015
Friday 11 Sep, 2015
Monday 14 Sep, 2015
Friday 18 Sep, 2015
Monday 21 Sep, 2015
Friday 25 Sep, 2015
Monday 28 Sep, 2015
Demo
Suppose I have 2 dates say 29 Aug 2014 and 3 Sep 2014. I need to display all dates between these to dates in the below format.
Aug 2014
29 Fri
30 Sat
31 Sun
Sept 2014
01 Mon
02 Tue
03 Wed
I know how to print all the dates like 29,30,31,1,2,3. But what I am unable to do is to get the month names in between.
Pretty easy question to be honest, pretty basic sollution possible..
$dateRange = new DatePeriod(
new DateTime('2014-07-28'),
new DateInterval('P1D'),
new DateTime('2014-08-04 00:00:01')
);
$month = null;
foreach ($dateRange as $date)
{
$currentMonth = $date->format('m Y');
if ($currentMonth != $month)
{
$month = $date->format('m Y');
echo $date->format('F Y').'<br />';
}
echo $date->format('d D').'<br />';
}
Above sollution results in:
July 2014
28 Mon
29 Tue
30 Wed
31 Thu
August 2014
01 Fri
02 Sat
03 Sun
Do mind it needs PHP >= 5.3 (due to the use of DatePeriod), but the actual logic to solve your question is easy to implement regardless of the used PHP version.
$timeS = strtotime("29 Aug 2014");
$timeE = strtotime("3 Sep 2014");
$monthS = -1;
$time = $timeS;
while ($time < $timeE) {
if ($monthS != date("n", $time)) {
echo date("M Y", $time) . "\n";
$monthS = date("n", $time);
}
echo date("d D", $time) . "\n";
$time = strtotime("+1 day", $time);
}
Edit: After doing it I'm pretty ok with #hindmost comment :)
I think , this is the complete code , as you wanted.
Executed code is here...
http://phpfiddle.org/main/code/3cbe-4855
<?php
$currentMonth = null;
$timeS = strtotime("29 Aug 2013");
$timeE = strtotime("3 Sep 2014");
$time = $timeS;
while ($time < $timeE) {
$month = date("M", $time);
$year = date("Y", $time);
if ($month != $currentMonth)
echo "<br /><h3>".$month."- ".$year."</h3>";
$currentMonth = $month;
echo "<br />".date("d D", $time);
$time = strtotime("+1 day", $time);
}
?>
In my script, I have a given end date. To get the start date, I subtract 23 months to the end date. Basically, what my script should do is to output 24 months (w/ year) - the last month/year to be printed should always be the specified end date.
For some reason, my script isn't returning my desired results. Given the $end = '2013-07-05', the script returns the result correctly. It prints out Aug 11 to Jul 13 which is correct.
But for some dates (e.g. $end = '2013-07-31'), the output is wrong. The result should be Sep 11 to Aug 13. But in this case, it outputs Aug 11 to Aug 13 which is absolutely wrong.
Here's my code:
<?php
$end = strtotime('2013-07-31 +1 month');
$date = strtotime('2013-07-31 -23 month');
$start = $month = $date;
$months = "";
while($month < $end)
{
$months .= date('M y', intval($month))." ";
$month = strtotime("+1 month", intval($month));
}
echo $months;
?>
I think there's something wrong with strtotime(). Thanks in advance.
You can't really use month calculations like that, especially when dealing with end-of-month values:
e.g. if it's July 31, what's -1 month to strtotime?
php > echo date('r', strtotime('2013-07-31 -1 month'));
Mon, 01 Jul 2013 00:00:00 -0600
A human would probably pick out June 30th, but strtotime isn't human. This DOES work for February 28th and generally any date where the day value is <= 28. Once you get into the 29,30,31 area, then you get these unexepected results
php > echo date('r', strtotime('2013-04-28 -1 month'));
Thu, 28 Mar 2013 00:00:00 -0600
How about
$endMonth = '8';
$year = '2013';
$i = 24;
while( $i > 0 ){
$month = ($endMonth - $i)%12;
if( $month == 0 ){
$year = $year - 1;
$month = 12;
}
$months .= date('M y', strtotime($year.'-'.$month.'-02'));
$i--;
}
Based on Marc B's answer I modified the script to deal with the 29,30,31 of each month. What I did was, if the date is 29, 30, or 31, it will be subtracted with 3 days so that the date will be either 28 or below and would work just fine with the current code that I have. It worked for me so I guess I'll just stick with this for now. Here's the updated code:
<?php
$dt = "2013-07-31";
$dy = strtotime($dt);
$day = date("d", $dy);
if (($day == 29) || ($day == 30) || ($day == 31)){
$dt = strtotime("$dt -3 days");
$dt = date('Y-m-d', $dt);
}
$end = strtotime("$dt +1 month");
$date = strtotime("$dt -23 month");
$start = $month = $date;
$months = "";
while($month < $end)
{
$months .= date('M y', intval($month))." ";
$month = strtotime("+1 month", intval($month));
}
echo $months;
?>
Thanks for your help and insights. :)
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
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 );