Related
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.
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
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.
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));
I think its possible but i cant come up with the right algorithm for it.
What i wanted to do was:
If today is monday feb 2 2009, how would i know the date of last week's tuesday? Using that same code 2 days after, i would find the same date of last week's tuesday with the current date being wednesday, feb 4 2009.
Most of these answers are either too much, or technically incorrect because "last Tuesday" doesn't necessarily mean the Tuesday from last week, it just means the previous Tuesday, which could be within the same week of "now".
The correct answer is:
strtotime('tuesday last week')
I know there is an accepted answer already, but imho it does not meet the second requirement that was asked for. In the above case, strtotime would yield yesterday if used on a wednesday. So, just to be exact you would still need to check for this:
$tuesday = strtotime('last Tuesday');
// check if we need to go back in time one more week
$tuesday = date('W', $tuesday)==date('W') ? $tuesday-7*86400 : $tuesday;
As davil pointed out in his comment, this was kind of a quick-shot of mine. The above calculation will be off by one once a year due to daylight saving time. The good-enough solution would be:
$tuesday = date('W', $tuesday)==date('W') ? $tuesday-7*86400+7200 : $tuesday;
If you need the time to be 0:00h, you'll need some extra effort of course.
PHP actually makes this really easy:
echo strtotime('last Tuesday');
See the strtotime documentation.
Working solution:
$z = date("Y-m-d", strtotime("last Saturday"));
$z = (date('W', strtotime($z)) == date('W')) ? (strtotime($z)-7*86400+7200) : strtotime($z);
print date("Y-m-d", $z);
you forgot strtotime for second argument of date('W', $tuesday)
hmm.
convert $tuesday to timestamp before "$tuesday-7*86400+7200"
mde.
// test: find last date for each day of the week
foreach (array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun') as $day) {
print $day . " => " . date('m/d/Y', last_dayofweek($day)) . "\n";
}
function last_dayofweek($day)
{
// return timestamp of last Monday...Friday
// will return today if today is the requested weekday
$day = strtolower(substr($day, 0, 3));
if (strtolower(date('D')) == $day)
return strtotime("today");
else
return strtotime("last {$day}");
}
<?php
$currentDay = date('D');
echo "Today-".$today = date("Y-m-d");
echo "Yesterday-".$yesterday = date("Y-m-d",strtotime('yesterday'));
echo "Same day last week-".$same_day_last_week = date("Y-m-d",strtotime('last '.$currentDay));
?>
Do not use manual calculation, use DateTime object instead. It has proper implementation, takes into account leap years, yeap seconds, etc.
$today = new \DateTime();
$today->modify('tuesday last week');
The modify method modifies the date relative to it's state, so if you set the date to a different date, it calculates it relative to it.
$date = new \DateTime('2020-01-01');
echo $date->format('Y-m-d'); // 2020-01-01
$date->modify('tuesday last week');
echo $date->format('Y-m-d'); // 2019-12-24