get next and previous day with PHP - php

I have got two arrows set up, click for next day, next two days, soon and previous day, two days ago, soon. the code seem not working? as it only get one next and previous day.
<a href="home.php?date=<?= date('Y-m-d', strtotime('-1 day', strtotime($date))) ?>" class="prev_day" title="Previous Day" ></a>
<a href="home.php?date=<?= date('Y-m-d', strtotime('+1 day', strtotime($date))) ?>" class="next_day" title="Next Day" ></a>
is there a way if i click the next button, the date will continously change for the next day. for a moment it will only get one day ahead

date('Y-m-d', strtotime('+1 day', strtotime($date)))
Should read
date('Y-m-d', strtotime(' +1 day'))
Update to answer question asked in comment about continuously changing the date.
<?php
$date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
$prev_date = date('Y-m-d', strtotime($date .' -1 day'));
$next_date = date('Y-m-d', strtotime($date .' +1 day'));
?>
Previous
Next
This will increase and decrease the date by one from the date you are on at the time.

Requirement: PHP 5 >= 5.2.0
You should make use of the DateTime and DateInterval classes in Php, and things will turn to be very easy and readable.
Example: Lets get the previous day.
// always make sure to have set your default timezone
date_default_timezone_set('Europe/Berlin');
// create DateTime instance, holding the current datetime
$datetime = new DateTime();
// create one day interval
$interval = new DateInterval('P1D');
// modify the DateTime instance
$datetime->sub($interval);
// display the result, or print_r($datetime); for more insight
echo $datetime->format('Y-m-d');
/**
* TIP:
* if you dont want to change the default timezone, use
* use the DateTimeZone class instead.
*
* $myTimezone = new DateTimeZone('Europe/Berlin');
* $datetime->setTimezone($myTimezone);
*
* or just include it inside the constructor
* in this form new DateTime("now", $myTimezone);
*/
References: Modern PHP, New Features and Good Practices
By Josh Lockhart

Use
$time = time();
For previous day -
date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time)- 1 ,date("Y", $time)));
For 2 days ago
date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time) -2 ,date("Y", $time)));
For Next day -
date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time)+ 1 ,date("Y", $time)));
For next 2 days
date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time) +2 ,date("Y", $time)));

Simply use this
echo date('Y-m-d',strtotime("yesterday"));
echo date('Y-m-d',strtotime("tomorrow"));

it is enough to call it this way:
<a href="home.php?date=<?= date('Y-m-d', strtotime('-1 day')) ?>" class="prev_day" title="Previous Day" ></a>
<a href="home.php?date=<?= date('Y-m-d', strtotime('+1 day')) ?>" class="next_day" title="Next Day" ></a>
Also see the documentation.

strtotime('-1 day', strtotime($date))
This returns the number of difference in seconds of the given date and the $date.so you are getting wrong result .
Suppose $date is todays date and -1 day means it returns -86400 as the difference and the when you try using date you will get 1969-12-31 Unix timestamp start date.

You could use 'now' as string to get today's/tomorrow's/yesterday's date:
$previousDay = date('Y-m-d', strtotime('now - 1day'));
$toDay = date('Y-m-d', strtotime('now'));
$nextDay = date('Y-m-d', strtotime('now + 1day'));

always make sure to have set your default timezone
date_default_timezone_set('Europe/Berlin');
create DateTime instance, holding the current datetime
$datetime = new DateTime();
create one day interval
$interval = new DateInterval('P1D');
modify the DateTime instance
$datetime->sub($interval);
display the result, or print_r($datetime); for more insight
echo $datetime->format('Y-m-d');
TIP:
If you don't want to change the default timezone, use the DateTimeZone class instead.
$myTimezone = new DateTimeZone('Europe/Berlin');
$datetime->setTimezone($myTimezone);
or just include it inside the constructor in this form new DateTime("now", $myTimezone);

Php script -1****its to Next Date
<?php
$currentdate=date('Y-m-d');
$date_arr=explode('-',$currentdate);
$next_date=
Date("Y-m-d",mktime(0,0,0,$date_arr[1],$date_arr[2]+1,$date_arr[0]));
echo $next_date;
?>**
**Php script -1****its to Next year**
<?php
$currentdate=date('Y-m-d');
$date_arr=explode('-',$currentdate);
$next_date=
Date("Y-m-d",mktime(0,0,0,$date_arr[1],$date_arr[2],$date_arr[0]+1));
echo $next_date;
?>

just in case if you want next day or previous day from today's date
date("Y-m-d", mktime(0, 0, 0, date("m"),date("d")-1,date("Y")));
just change the "-1" to the "+1"
regards, Yosafat

Very easy with the dateTime() object, too.
$tomorrow = new DateTime('tomorrow');
echo $tomorrow->format("Y-m-d"); // Tomorrow's date
$yesterday = new DateTime('yesterday');
echo $yesterday->format("Y-m-d"); // Yesterday's date

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);

php add x weeks to a date and then find the next given day

I can add x week to my date
//$ultima_azione <--- 2015/07/15
//$data['intervallo'] <---- 5
$mydate = date("Y-m-d",strtotime($ultima_azione." +".$data['intervallo']." weeks"));
now how can i give a day starting from that week
example:
//$mydate + "next Monday" -----> final date
and this ve to work like, if today is Monday and i add weeks to jump to an other Monday and then i select the next Monday the week don't ve to change
The simplest way would be to use strtotime. It can do date calculations based on a textual representation of the delta:
$mydate = strtotime('+3 weeks');
It also accepts a second parameter, which is a timestamp to start from when doing the calculation, so after you get the offset in weeks, you can pass the new date to a second calculation:
// Get three weeks from 'now' (no explicit time given)
$mydate = strtotime('+3 weeks');
// Get the Monday after that.
$mydate = strtotime('next Monday', $mydate);
See strtotime documentation for more examples of notations that you can use.
I would highly recommend using PHP's built-in DateTime class for any date and time logic. It's a much better API than the older date and time functions and creates much cleaner and easier to read code.
For example:
// Current date and number of weeks to add
$date = '2015/07/15';
$weeks = 3;
// Create and modify the date.
$dateTime = DateTime::createFromFormat('Y/m/d', $date);
$dateTime->add(DateInterval::createFromDateString($weeks . ' weeks'));
$dateTime->modify('next monday');
// Output the new date.
echo $dateTime->format('Y-m-d');
References:
DateTime.
DateTime::createFromFormat
DateTime::add
DateTime::modify
DateInterval::createFromDateString
DateTime::format
Are you looking for something like this?
$today = time();
$weeks = 2;
// timestamp 2 weeks from now
$futureWeeks = strtotime("+ ".$weeks." weeks");
// the next monday after the timestamp date
$futureMonday = strtotime("next monday",$futureWeeks);
echo date("Y-m-d", $futureMonday);
// or in one line
echo date("Y-m-d", strtotime("next monday", strtotime("+ ".$weeks." weeks")));
PHP is using an unix timestamp for date calculations. Functions as date() and strtotime() using a timestamp as an optional second parameter. This is used a reference for formatting and calculations. If no timestamp is passed to the function the current timestamp is used (time()).
I have the answer here. This will show the next wednesday every 2 weeks and the first date to start from would be the 10th.
I have also added in an estimated delivery which would be 6 weeks after that date.
We will be placing our next order for this on:
<?php
$date = '2020/05/26';
$weeks = 2;
$dateTime = DateTime::createFromFormat('Y/m/d', $date);
$dateTime->add(DateInterval::createFromDateString($weeks . ' weeks'));
$dateTime->modify('wednesday');
echo $dateTime->format('d/m/Y');
?>
Expected delivery for the next order will be:
<?php
$date = '2020/05/26';
$weeks = 2;
$dateTime = DateTime::createFromFormat('Y/m/d', $date);
$dateTime->add(DateInterval::createFromDateString($weeks . ' weeks'));
$dateTime->modify('+42 days next wednesday');
echo $dateTime->format('d/m/Y');
?>
If anyone can confirm this is correct that would be great.

add day to current date

add a day to date, so I can store tomorrow's date in a variable.
$tomorrow = date("Y-m-d")+86400;
I forgot.
date returns a string, whereas you want to be adding 86400 seconds to the timestamp. I think you're looking for this:
$tomorrow = date("Y-m-d", time() + 86400);
I'd encourage you to explore the PHP 5.3 DateTime class. It makes dates and times far easier to work with:
$tomorrow = new DateTime('tomorrow');
// e.g. echo 2010-10-13
echo $tomorrow->format('d-m-Y');
Furthermore, you can use the + 1 day syntax with any date:
$xmasDay = new DateTime('2010-12-24 + 1 day');
echo $xmasDay->format('Y-m-d'); // 2010-12-25
date() returns a string, so adding an integer to it is no good.
First build your tomorrow timestamp, using strtotime to be not only clean but more accurate (see Pekka's comment):
$tomorrow_timestamp = strtotime("+ 1 day");
Then, use it as the second argument for your date call:
$tomorrow_date = date("Y-m-d", $tomorrow_timestamp);
Or, if you're in a super-compact mood, that can all be pushed down into
$tomorrow = date("Y-m-d", strtotime("+ 1 day"));
Nice and obvious:
$tomorrow = strtotime('tomorrow');
You can use the add method datetime class.
Eg, you want to add one day to current date and time.
$today = new DateTime();
$today->add(new DateInterval('P1D'));
Further reference php datetime add
Hope this helps.
I find mktime() most useful for this sort of thing. E.g.:
$tomorrow=date("Y-m-d", mktime(0, 0, 0, date("m"), date("d")+1, date("Y")));

Given a time, how can I find the time one month ago

Given a time, how can I find the time one month ago.
strtotime( '-1 month', $timestamp );
http://php.net/manual/en/function.strtotime.php
In php you can use strtotime("-1 month"). Check out the documentation here: http://ca3.php.net/strtotime
We can achieve same by using PHP's modern date handling. This will require PHP 5.2 or better.
// say its "2015-11-17 03:27:22"
$dtTm = new DateTime('-1 MONTH', new DateTimeZone('America/Los_Angeles')); // first argument uses strtotime parsing
echo $dtTm->format('Y-m-d H:i:s'); // "2015-10-17 03:27:22"
Hope this adds some more info for this question.
<?php
$date = new DateTime("18-July-2008 16:30:30");
echo $date->format("d-m-Y H:i:s").'<br />';
date_sub($date, new DateInterval("P1M"));
echo '<br />'.$date->format("d-m-Y").' : 1 Month';
?>
PHP 5.2=<
$date = new DateTime(); // Return Datetime object for current time
$date->modify('-1 month'); // Modify to deduct a month (Also can use '+1 day', '-2 day', ..etc)
echo $date->format('Y-m-d'); // To set the format
Ref: http://php.net/manual/en/datetime.modify.php
This code is for getting 1 month before not 30 days
$date = "2016-03-31";
$days = date("t", strtotime($date));
echo date("Y-m-d", strtotime( "-$days days", strtotime($date) ));
These answers were driving me nuts. You can't subtract 31 days and have a sane result without skipping short months.
I'm presuming you only care about the month, not the day of the month, for a case like filtering/grouping things by year and month.
I do something like this:
$current_ym = date('ym',strtotime("-15 days",$ts));

adding 1 day to a DATETIME format value

In certain situations I want to add 1 day to the value of my DATETIME formatted variable:
$start_date = date('Y-m-d H:i:s', strtotime("{$_GET['start_hours']}:{$_GET['start_minutes']} {$_GET['start_ampm']}"));
What is the best way to do this?
There's more then one way to do this with DateTime which was introduced in PHP 5.2. Unlike using strtotime() this will account for daylight savings time and leap year.
$datetime = new DateTime('2013-01-29');
$datetime->modify('+1 day');
echo $datetime->format('Y-m-d H:i:s');
// Available in PHP 5.3
$datetime = new DateTime('2013-01-29');
$datetime->add(new DateInterval('P1D'));
echo $datetime->format('Y-m-d H:i:s');
// Available in PHP 5.4
echo (new DateTime('2013-01-29'))->add(new DateInterval('P1D'))->format('Y-m-d H:i:s');
// Available in PHP 5.5
$start = new DateTimeImmutable('2013-01-29');
$datetime = $start->modify('+1 day');
echo $datetime->format('Y-m-d H:i:s');
If you want to do this in PHP:
// replace time() with the time stamp you want to add one day to
$startDate = time();
date('Y-m-d H:i:s', strtotime('+1 day', $startDate));
If you want to add the date in MySQL:
-- replace CURRENT_DATE with the date you want to add one day to
SELECT DATE_ADD(CURRENT_DATE, INTERVAL 1 DAY);
The DateTime constructor takes a parameter string time. $time can be different things, it has to respect the datetime format.
There are some valid values as examples :
'now' (the default value)
2017-10-19
2017-10-19 11:59:59
2017-10-19 +1day
So, in your case you can use the following.
$dt = new \DateTime('now +1 day'); //Tomorrow
$dt = new \DateTime('2016-01-01 +1 day'); //2016-01-02
Use strtotime to convert the string to a time stamp
Add a day to it (eg: by adding 86400 seconds (24 * 60 * 60))
eg:
$time = strtotime($myInput);
$newTime = $time + 86400;
If it's only adding 1 day, then using strtotime again is probably overkill.
You can use
$now = new DateTime();
$date = $now->modify('+1 day')->format('Y-m-d H:i:s');
You can use as following.
$start_date = date('Y-m-d H:i:s');
$end_date = date("Y-m-d 23:59:59", strtotime('+3 days', strtotime($start_date)));
You can also set days as constant and use like below.
if (!defined('ADD_DAYS')) define('ADD_DAYS','+3 days');
$end_date = date("Y-m-d 23:59:59", strtotime(ADD_DAYS, strtotime($start_date)));
I suggest start using Zend_Date classes from Zend Framework. I know, its a bit offtopic, but I'll like this way :-)
$date = new Zend_Date();
$date->add('24:00:00', Zend_Date::TIMES);
print $date->get();
Using server request time to Add days. Working as expected.
25/08/19 => 27/09/19
$timestamp = $_SERVER['REQUEST_TIME'];
$dateNow = date('d/m/y', $timestamp);
$newDate = date('d/m/y', strtotime('+2 day', $timestamp));
Here '+2 days' to add any number of days.
One liner !
echo (new \DateTime('2016-01-01 +1 day'))->format('Y-m-d H:i:s');

Categories