get date of next 4 days - php

The following code worked before, but failed to get the next 4 days of today 2011-11-04
$draw_date = '2011-11-04';
$ts = strtotime($draw_date) + 86400*4;
$ddate = date('Y-m-d', $ts);
echo $ddate;
The code above print 2011-11-07, but what I expected is 2011-11-08. It works if I set draw_date = '2011-10-04' or '2011-12-04'. Very weird! Can anyone explain why?
Thanks in advance.

Don't forget there's a DST switchover on November 6th. That makes 4days-from-now actually be 86400*4 + 3600 for the extra hour.

You can use:
$ts = strtotime($draw_date) ;
strtotime('+4 day', $ts);

Related

PHP date + 1 year is returning a date slightly less than 1 year [duplicate]

I'm trying to get a date that is one year from the date I specify.
My code looks like this:
$futureDate=date('Y-m-d', strtotime('+one year', $startDate));
It's returning the wrong date. Any ideas why?
$futureDate=date('Y-m-d', strtotime('+1 year'));
$futureDate is one year from now!
$futureDate=date('Y-m-d', strtotime('+1 year', strtotime($startDate)) );
$futureDate is one year from $startDate!
To add one year to todays date use the following:
$oneYearOn = date('Y-m-d',strtotime(date("Y-m-d", mktime()) . " + 365 day"));
For the other examples you must initialize $StartingDate with a timestamp value
for example:
$StartingDate = mktime(); // todays date as a timestamp
Try this
$newEndingDate = date("Y-m-d", strtotime(date("Y-m-d", strtotime($StaringDate)) . " + 365 day"));
or
$newEndingDate = date("Y-m-d", strtotime(date("Y-m-d", strtotime($StaringDate)) . " + 1 year"));
//1 year from today's date
echo date('d-m-Y', strtotime('+1 year'));
//1 year from from specific date
echo date('22-09-Y', strtotime('+1 year'));
hope this simpler bit of code helps someone in future :)
Try: $futureDate=date('Y-m-d',strtotime('+1 year',$startDate));
just had the same problem, however this was the simplest solution:
<?php (date('Y')+1).date('-m-d'); ?>
// Declare a variable for this year
$this_year = date("Y");
// Add 1 to the variable
$next_year = $this_year + 1;
$year_after = $this_year + 2;
// Check your code
echo "This year is ";
echo $this_year;
echo "<br />";
echo "Next year is ";
echo $next_year;
echo "<br />";
echo "The year after that is ";
echo $year_after;
I prefer the OO approach:
$date = new \DateTimeImmutable('today'); //'today' gives midnight, leave blank for current time.
$futureDate = $date->add(\DateInterval::createFromDateString('+1 Year'))
Use DateTimeImmutable otherwise you will modify the original date too!
more on DateTimeImmutable: http://php.net/manual/en/class.datetimeimmutable.php
If you just want from todays date then you can always do:
new \DateTimeImmutable('-1 Month');
If you are using PHP 5.3, it is because you need to set the default time zone:
date_default_timezone_set()
strtotime() is returning bool(false), because it can't parse the string '+one year' (it doesn't understand "one"). false is then being implicitly cast to the integer timestamp 0. It's a good idea to verify strtotime()'s output isn't bool(false) before you go shoving it in other functions.
From the docs:
Return Values
Returns a timestamp on success, FALSE
otherwise. Previous to PHP 5.1.0, this
function would return -1 on failure.
Try This
$nextyear = date("M d,Y",mktime(0, 0, 0, date("m",strtotime($startDate)), date("d",strtotime($startDate)), date("Y",strtotime($startDate))+1));
There is also a simpler and less sophisticated solution:
$monthDay = date('m/d');
$year = date('Y')+1;
$oneYearFuture = "".$monthDay."/".$year."";
echo"The date one year in the future is: ".$oneYearFuture."";
You can use strtotime() to get future time.
//strtotime('+1 day');
//strtotime('+1 week');
//strtotime('+1 month');
$now = date('Y-m-d');
$oneYearLaterFromNow = date('Y-m-d', strtotime('+1 year'));
$oneYearLaterFromAnyDate = date('Y-m-d', strtotime('+1 year', strtotime($anyValidDateString)));
In my case (i want to add 3 years to current date) the solution was:
$future_date = date('Y-m-d', strtotime("now + 3 years"));
To Gardenee, Treby and Daniel Lima:
what will happen with 29th February? Sometimes February has only 28 days :)
My solution is: date('Y-m-d', time()-60*60*24*365);
You can make it more "readable" with defines:
define('ONE_SECOND', 1);
define('ONE_MINUTE', 60 * ONE_SECOND);
define('ONE_HOUR', 60 * ONE_MINUTE);
define('ONE_DAY', 24 * ONE_HOUR);
define('ONE_YEAR', 365 * ONE_DAY);
date('Y-m-d', time()-ONE_YEAR);

Get current week start/end date with DST

I was using the following code for some months now without any issue in order to get the current week start/end date (Monday/Sunday):
date_default_timezone_set('Europe/Bucharest'); //this is the default in php.ini
$monday = strtotime('next Monday -1 week');
$monday = date('w', $monday)==date('w') ? $monday+7*86400 : $monday;
$sunday = strtotime(date("Y-m-d",$monday)." +6 days");
echo "Current week start/end date:<br>";
echo $this_week_sd = date("Y-m-d",$monday)."<br>";
echo $this_week_ed = date("Y-m-d",$sunday)."<br>";
//Expected result:
2018-10-29
2018-11-04
However, as of Today this for some reason has been offset by 1 day:
//Actual incorrect result:
2018-10-28
2018-11-03
Then I remembered that Yesterday the clock went back 1 hour due to DST, so I decided to change the timezone from Europe/Bucharest to Europe/Istanbul which still has a +3 hours advance against GMT:
date_default_timezone_set('Europe/Istanbul');
//Now the result is correct:
2018-10-29
2018-11-04
Question is, how can I offset DST in the current code so that I could keep the relative week dates in accordance with Europe/Bucharest timezone? Any pointers or explanations would be appreciated. Thank you.
If you just want to fix your current Code, just replace your three "ugly" ;-) lines:
$monday = strtotime('next Monday -1 week');
$monday = date('w', $monday)==date('w') ? strtotime(date("Y-m-d",$monday)." +7 days") : $monday;
$sunday = strtotime(date("Y-m-d",$monday)." +6 days");
with those "nice" one, and it will work.
$monday = strtotime('monday this week');
$sunday = strtotime('sunday this week');
PHPs relative Date Expressions can handle this nice.
I would do this using the DateTime class and keep everything in UTC so you never have to worry about daylight savings time:
$today = new DateTime('now', new DateTimeZone('UTC'));
$day_of_week = $today->format('w');
$today->modify('- ' . (($day_of_week - 1 + 7) % 7) . 'days');
$sunday = clone $today;
$sunday->modify('+ 6 days');
echo $today->format('Y-m-d') . "\n";
echo $sunday->format('Y-m-d');
Output:
2018-10-29
2018-11-04
Demo on 3v4l.org
I am aware that there is more than one way to skin a cat, but in this case I was interested in how to fix my current code and more importantly to find out what's wrong with it.
Thank you all for your suggestions, especially to #misorude for pointing out the obvious flaw in my initial code, whereas "not every day has 86400 seconds", which is especially true during DST.
So here's the updated working code using relative "days" instead of fixed seconds amount:
$monday = strtotime('next Monday -1 week');
$monday = date('w', $monday)==date('w') ? strtotime(date("Y-m-d",$monday)." +7 days") : $monday;
$sunday = strtotime(date("Y-m-d",$monday)." +6 days");
echo "This week start/end date:<br>";
echo $this_week_sd = date("Y-m-d",$monday)."<br>";
echo $this_week_ed = date("Y-m-d",$sunday)."<br>";
//output:
This week start/end date:
2018-10-29
2018-11-04
Once again, thank you all for your inputs. Much appreciated!

date half month not working

I tried to do like this
date('Y-m-d', strtotime('0.5 months'));
But it gives me date 1970-01-01
Expected date is 2017-10-15
So the question is why the half month is not working?
You can't use non-integers in a strtotime() relative date format:
number [+-]?[0-9]+
To make this work, you can use either 2 weeks or 15 days (note that these two return different days, since 2 weeks is 14 days):
<?php
echo date("Y-m-d", strtotime("2 weeks")).PHP_EOL; // 2017-10-15
echo date("Y-m-d", strtotime("15 days")).PHP_EOL; // 2017-10-16
echo date("Y-m-d", strtotime("+.5 months")).PHP_EOL; // not valid, returns 1970-01-01
Demo
I think you forgot the Plus singn
Please try with below
date('Y-m-d', strtotime('+ 0.5 months'));
or
date('Y-m-d', strtotime('+ 15 days'));
(If you convert in days)
hope will help you
I'm looking for a solution using only php relative time for a half month. The problem with the previous answers is that they don’t take into account the fluctuation in the amount of days per month. Consider this:
$time = strtotime('last day of feb 2019');
$time = strtotime('-2 weeks', $time);
$formatted_date = date('m/d', $time);
Output is 02/14 which is exactly in the middle of the month. But what about this:
$time = strtotime('last day of jan');
$time = strtotime('-2 weeks', $time);
$formatted_date = date('m/d', $time);
Output is 01/17, which is 1-2 days off from the true middle of the month (01/15.5) depending on if you round up or down.
Also, per the answer with strtotime('+0.5 months'), I know this was addressed, but this is an excerpt straight from the PHP docs:
number is an integer number; if a decimal number is given, the dot (or comma) is likely interpreted as delimiter. For instance, '+1.5 hours' is parsed like '+1 5 hours', not as '+1 hour +30 minutes'.
I’ve experimented with quite a few phrasings to get to the true middle of the month, and I’ve come to the conclusion that it isn’t possible with relative formats alone. So here is my solution:
<?php
function middleOfMonth( $time ) {
$n = cal_days_in_month( CAL_GREGORIAN, date('n', $time), date('Y', $time) );
return $n / 2;
}
$time = strtotime('jan next year');
$middle = middleOfMonth( $time ); // result is 15.5
echo( ceil( $middle ) ); // outputs 16
echo( floor( $middle ) ); // outputs 15

Get 30 days back date along with time

I want to calculate EXACT past 30 days time period in php from now (for example 30 aug 14 23:06) to 30 days back (for example 1 aug 14 23:06). I wrote this where current datetime goes in $d1 and past 30 days datetime goes in $d2 but somehow i am not getting correct results. Any idea?
$url=$row["url"];
$pageid=getPageID($url);
$date=date('y-m-d g:i');
$d1=strtotime($date);
$d2=date(strtotime('today - 30 days'));
Thanks
The problem is likely caused by the malformed date() call. The first argument passed to date() should be the format (as shown in the Docs) and the second should be an optional timestamp.
Try this:
$d2 = date('c', strtotime('-30 days'));
PHPFiddle
As a short aside, the whole snippet can be simplified as follows:
$url = $row["url"];
$pageid = getPageID($url);
$date = date('y-m-d g:i');
$d1 = time();
$d2 = date('y-m-d g:i', strtotime('-30 days'));
You can also use the DateTime class's sub() method together with an DateInterval:
$now = new DateTime();
$back = $now->sub(DateInterval::createFromDateString('30 days'));
echo $back->format('y-m-d g:i');
if you would like to get out put as 2014-08-01 then try the below code. thanks
$date = '2014-08-30 23:06';
$new_date = date('Y-m-d G:i', strtotime($date.' - 29 days'));
echo "30 days back is " . $new_date;
From your brief description and example given, I believe that you want the date to be 30 days back and time to be the same as of now. The below code will serve this purpose. Thanks.
<?php
$date=date('y-m-d g:i');
$time=date('g:i');
echo "Todays date:" . $date. "<br>";
$d2 = date('y-m-d', strtotime('-30 days'));
echo "30 days back:" . $d2 . ' ' .$time;
?>
Try:
echo date("Y-m-d h:i:s",strtotime('-30 days'));
For more detail click here
Very simple two lines of code
$date = new DateTime();
echo $date->modify('-30 day')->format('y-m-d g:i');
I know you said with PHP, however, I can't imagine not getting the records from a DB. If you want to do so from the DB,use:
$sql='SELECT * FROM myTable WHERE date > CURRENT_DATE - INTERVAL 30 DAY';
$pdo->query($sql);
Very simple one lines of code:
echo (new DateTime())->modify('-30 day')->format('y-m-d g:i');
In the example below, it makes no sense if the variable $date is not
used anywhere else!
$date = new DateTime();
echo $date->modify('-30 day')->format('y-m-d g:i');
Sample answer is
$dateBack30Days=date('Y-m-d g:i', strtotime('-30 days'));

adding weekdays - clears the time

I've tired to add 10 weekdays to now. Everything is OK, but it clears the time part. Do you know why?
$now = date("Y-m-d H:i:s");
echo $now.'<br>';
$mod = strtotime($now." +10 weekdays");
echo $mod.'<br>';
echo date("Y-m-d H:i:s",$mod).'<br>';
Output:
2011-05-23 14:34:02
1307311200
2011-06-06 00:00:00
My expected output were:
2011-06-06 14:34:02
Thanks.
Looks like a difference in interpretation.
You could do the following to enforce the time:
<?php
$date = date("Y-m-d");
$time = date("H:i:s");
echo $date.' '.$time.'<br>';
$mod= strtotime($date." +10 weekdays $time");
echo $mod.'<br>';
echo date("Y-m-d H:i:s",$mod).'<br>';
There are several examples on the PHP documentation which can help you add days while still preserving the times.

Categories