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
Related
I have to get a date which is 6 months added with specific date.
I used the following code
$start_date = "2016-08-30";
$end_date= date( "Y-m-d", strtotime( "$start_date +6 months" ) );
echo $end_date;
which gave result as 2017-03-02
Then I changed the start date in code as below
$start_date = "2016-09-01";
$end_date= date( "Y-m-d", strtotime( "$start_date +6 months" ) );
echo $end_date;
which is giving result as 2017-03-01
Why is this happening at first place? Is there anything wrong with my code?
Using Mysql query
SELECT DATE_ADD('2016-08-30', INTERVAL 6 MONTH)
gives result 2017-02-28
Which is the right solution to get the correct date?
This happens due to PHP's behavior. In this case 6 months are added which gives february(it has 28 days) so it adds three more days , but in MySQL it adds only months.
To solve this use last day of 6 month or last day of sixth month instead of +6 months
Code
$date = new DateTime( '2016-08-30' );
echo $date->format( 'Y-m-d' ), "\n";
$date->modify( 'last day of sixth month' );
echo $date->format( 'Y-m-d' ), "\n";
Code Demo
Output
2016-08-30
2017-02-28
Another Solution
$date = new DateTime( '2016-08-25' );
echo $date->format('Y-m-d'),"\n";
$day = $date->format('j');
$date->modify('first day of sixth month');
$date->modify('+' . (min($day, $date->format('t')) - 1) . ' days');
echo $date->format('Y-m-d');
Code Demo
Output
2016-08-25
2017-02-25
Also refer Relative Formats
This function DOES NOT work from left-to-right as one would think. This function parses the string as a whole, then applies the intervals by size (year, month, ...). Take the following example:
<?php
$Date = strtotime('2011-02-22'); // February 22nd, 2011. 28 days in this month, 29 next year.
echo date('n/j/Y', strtotime('+1 year, +7 days', $Date)); // add 1 year and 7 days. prints 2/29/2012
echo "<br />";
echo date('n/j/Y', strtotime('+7 days, +1 year', $Date)); // add 7 days and 1 year, but this also prints 2/29/2012
echo "<br />";
echo date('n/j/Y', strtotime('+1 year', strtotime('+7 days', $Date))); // this prints 3/1/2012, what the 2nd would do if it was left-to-right
?>
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.
Here's a summary of the issue: On Sundays, strtotime('this week') returns the start of next week.
In PHP, the week seems to start on Monday. But, on any day except Sunday, this code
echo date('Y-m-d', strtotime('monday this week', strtotime('last sunday')));
Outputs the date of this week's Monday, when it seems like it should be outputting last weeks Monday. It seems like, in this case, PHP is treating both Sunday and Monday as the the start of the week. It's now Monday, Dec 10, 2012, or 2012-12-10. date('Y-m-d', strtotime('sunday last week')) returns 2012-12-09 - yesterday.
Is this a bug, or am I missing something? It seems like a bug this obvious should be fairly well known, but I can't find anything about it. Is the only way to get the start of the week to use some special handling for Sundays?
$week_offset = (int) 'sunday' == date('l');
$week_start = strtotime("-$week_offset monday"); // 1 or 0 Mondays ago
As far as I can tell, this is a bug. I see no logical reason why strtotime('this week'); should return a future date. This is a pretty major bug. In my particular case, I had a leaderboard that showed the users with the most points since the beginning of the week. But on Sundays, it was empty because strtotime returned a timestamp for a future date. I was doubtful, because just I don't know how this could have gone unnoticed, but I couldn't find any other reports of this bug.
Thanks for all your time and help, folks.
This answer is late, but it's something that I've been struggling with. Every solution I've tried so far has malfunctioned for one reason or another. This is what I ended up with that worked for me. (though it may be look pretty, it at least works).
$thisMonday = strtotime('next Monday -1 week', strtotime('this sunday'));
Here is how you can get Monday of current week:
echo date("Y-m-d", strtotime(date('o-\\WW')));
It's not ideal but this is what I resorted to using:
if(date('N') == 7) {
$date = date('Y-m-d',strtotime('monday last week'));
} else {
$date = date('Y-m-d',strtotime('monday this week'));
}
I think the only problem with your coding is TimeZone.
Solution:
Set your own time Zone. Here is the example of my own time zone:
Example
date_default_timezone_set('Asia/Kolkata');
Set the above line before calling any time function.
Have a nice day.
I think instead of trying
echo date('Y-m-d', strtotime('monday this week', strtotime('last sunday')));
you should try
echo date('Y-m-d', strtotime('monday last week'));
Try this code
// set current date
$date = date("m/d/Y");
$ts = strtotime($date); // also $ts = time();
// find the year and the current week
$year = date('o', $ts);
$week = date('W', $ts);
// print week for the current date
$i = 1; // 1 denotes the first day of week
$ts = strtotime($year.'W'.$week.$i);
echo $day = date("l", $ts); // generate the name of day
echo "<br>";
echo $day = date("Y-m-d", $ts); // generate the date
You will get the the date of current week, whether you are on monday you will get the date of that monday.
If you want the most recent monday:
function mostRecentMonday(){
if(date("w") == 1){
return strtotime("midnight today");
} else {
return strtotime("last monday");
}
}
Easy to modify to use DateTime, or, to even specify a different date to use as the base.
Based on Bryant answer :
$first_week_date = date('d F Y', strtotime('next Monday -1 week', strtotime('this sunday')));
$last_week_date = date('d F Y', strtotime('next Monday -1 week + 6 days', strtotime('this sunday')));
This is for thos looking for a friendly solution that works with any day.
function getWeekStart($week_start_day = "Monday") {
$week_days = array("Sunday"=>0,"Monday"=>1,"Tuesday"=>2,"Wednesday"=>3,"Thursday"=>4,"Friday"=>5,"Saturday"=>6,);
if(!isset($week_days[$week_start_day])) {
return false;
} else {
$start_day = $week_days[$week_start_day];
$today = date("w");
$one_day = (60 * 60 * 24);
if($today < $start_day) {
$days_difference = 7 - ($start_day - $today);
} else {
$days_difference = ($today - $start_day);
}
$week_starts = strtotime(date("Y-m-d 00:00:00")) - ($one_day * $days_difference);
return $week_starts;
}
}
//Test: If today is Monday, it will return today's date
echo date("Y-m-d H:i:s", getWeekStart("Monday"));
I'm trying to get php to calculate a date that was one year and one day ago. I have this:
$date = date(strtotime('-366 days'));
$oneyear_oneday = date("Y-m-d H:i:s", $date);
$date = date(strtotime('-1 year'));
$oneyear = date("Y-m-d H:i:s", $date);
However, due to it being a leap year, both $oneyear and $oneyear_oneday provide the same output. Does anyone know how I can calculate this correctly?
ie if it's 3pm on 15th August 2012, I want the output to be 3pm on the 15th August 2011
with PHP5.3,
$date = new DateTime();
$interval = new DateInterval("P1Y");
$newdate = $date->sub($interval);
First, subtract one year. Then, subtract one day from the result:
$date = strtotime('-1 day', strtotime('-1 year'));
$oneyear_oneday = date("Y-m-d H:i:s", $date);
You can try to use mktime()...
Both calculations are correct. But if you want to get the same date, but one year before, you should simply use '-1 year'. The string '-366 days' is only correct in leap years.
$date = strtotime('2010-01-01 -1 year');
echo date('Y-m-d', $date);
The output stream looks like,
2009-01-01
Go this Link for more reference
so i have a date format like 07-09-10 and i want to know how to get ago from that date and if i can have a conditional like
if(is_date_with_1_week_of_above_date){
//do something
}
For checking date with relation to the Current Timestamp
if( strtotime( '-1 week' )>=$dateToCheck ) {
# $dateToCheck is within the last week
}
The other responses have good solutions for simple checking whether two date/times are within 1 week of each other - no point me repeating them.
Your date doesn't make clear the format (is it MM-DD-YY, DD-MM-YY, YY-MM-DD, etc.)? But an example using ISO 8601 date format is this:
$oneWeekAgo = strftime("%Y-%m-%d", strtotime("2010-07-09") - 60*60*24*7);
For a comparison, you can use the UNIX timestamp values
$date = "2010-07-09";
$compareDate = "2010-07-03";
$curTimestamp = strtotime($date);
$compareTimestamp = strtotime($compareDate);
if(abs($curTimestamp - $compareTimestamp) < 60*60*24*7)
{
// within 1 week
}
Edit
Per the comment on the date format, dd-mm-yy is a recognized format for dates, but mm-dd-yy is not in strtotime as seen here:
http://www.php.net/manual/en/datetime.formats.date.php
For it to work, you'd have to convert the dashes to slashes.
Also, if you're looking if the date is specifically one week prior,
$date = str_replace('-','/',"07-10-10");
$compareDate = str_replace('-','/',"07-03-10");
$curDate = strftime("%m/%d/%y", strtotime($date));
$compareDate = strftime("%m/%d/%y", strtotime($compareDate) + 60*60*24*7);
if($curDate == $compareDate)
{
// is one week prior
echo "OK";
}
Depending on your Time Zone, some days might have only 23 hours, so you can not use as a rule that a day has (60 seconds * 60 minutes * 24 hours) and with this, to calculate a specific date.
Specifying a date:
$specific_date = date( "Y-m-d" ); // for today
or
$specific_date = date( "Y-m-d", $timestamp ); // where timestamp is: Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
The answer will be
$date = strtotime( $specific_date . " -1 week" );