strtotime() in PHP is quite powerfull function. One of it's features is relative dates.
For example this command:
echo date('Y-m-d', strtotime('Sunday this week'));
produces 2016-02-14 on my machine (today is "2016-02-12", Friday). Thus it supposes that first day of week is Monday. However in different locales countries first day of week is different.
Is there a way to change this behaviour and make strtotime() think that first week day is Sunday?
As discussed in the comments of the question, it may be better to rely on a custom function, which is tested and will most probably produce the same result on every machine.
A function like this could be:
<?php
function x() {
return date('Y-m-d', date('N')==7 ? strtotime('today') : strtotime('last sunday'));
}
echo x();
You find a demo here.
If you have many machines to deploy your code to, you could additionally include a test script in the installation process which tests if it gets correct results from this (and other things that may vary depending on installation).
PHP 5.5 introduced the Internationalization extension, which among many useful functions provides and IntCalendar class. It has a static function getFirstDayOfWeek which can be used to get the first day of the week, based a locale.
Straight from the docs:
ini_set('date.timezone', 'UTC');
$cal1 = IntlCalendar::createInstance(NULL, 'es_ES');
var_dump($cal1->getFirstDayOfWeek()); // Monday
Related
Does PHP provide a way to set the system date within a script?
i.e. so that I can make date('Y') return 1999 even though it's currently 2021.
I want to be able to quickly set the system date for debugging/testing purposes.
Perhaps "system date" is the wrong phrase. I only want it to be changed for the same script, whilst it's running.
Manipulating the server date for a test creates a host of other problems. Don't do it!
You can always use a timestamp as a second parameter in your script. With strtotime() you can test the script with any date.
$ts = time();
$ts = strtotime('1999-01-01');
echo date('Y', $ts); //1999
After the test, the line is commented out with strtotime and the time stamp is then initialized with time(). The date ('Y') then behaves like without a second parameter.
$ts = time();
//$ts = strtotime('1999-01-01');
echo date('Y', $ts); //2021
I don't think there is a way using strictly PHP, however according to This answer, you can use shell_exec("date 09-09-99") to run a shell command and set the time of the system like that.
I wouldn't recommend it though, since it could mess with something else.
I try to find an answer but without result
the problem is:
in sunday function return date for Monday next week
$date = new DateTime();
$date->setTimezone(new DateTimeZone('Europe/Moscow'));
$date->setTimestamp(strtotime('Monday this week'));
echo $date->format("d.m.Y");
but in other days (except Sunday) its return correct value of Monday.
I ever set locale manualy , which has a monday - the first day of week, but PHP "think" the Sunday is still firs day. is it bug ?? or i do some wrong ?
There seem to be known idiosyncrasies with strtotime. It's mentioned in the comments:
http://www.php.net/manual/en/datetime.formats.relative.php#108317
They don't mention different locales specifically but it would be extremely unsurprising if strtotime() does not correctly behave for next/this week under different locales.
Try this Monday or next Monday and see if one of those gets what you want.
I'm trying to write a bit of php to determine the date (Y-m-d format) for the next occurrence of a given weekday.
date('Y-m-d', strtotime('next monday'));
is returning
2011-08-29
instead of
2011-08-22
on my server. Not sure why. My server is an EC2 instance in Amazon's US East-Coast data center and it's currently 2011-08-21 9:40:00.
EDIT 1
Also date('Y-m-d', strtotime('next sunday')); returns 2011-08-28 instead of today. I tried out this code on http://writecodeonline.com/php/ ... beginning to think that tester is inaccurate.
Just because your server is set to a certain timezone doesn't necessarily mean PHP will be acting on the same timezone. It is already Monday, August 22, 2011 in Europe, which also includes UTC. If your PHP is acting on this timezone, "next Monday" would be Aug. 29.
You should double-check your timezone settings in PHP. You can either run date_default_timezone_get() to check what settings your installation is using, or try forcing your PHP script to use the timezone you expect with date_default_timezone_set("America/New_York"); and seeing if you get the result you expect.
I just tested this:
date_default_timezone_set("America/New York");
echo date('Y-m-d', strtotime('next monday')); // prints 2011-08-22
date_default_timezone_set("UTC");
echo date('Y-m-d', strtotime('next monday')); // prints 2011-08-29
I think that's the expected behaviour, since Monday hasn't passed strtotime sees it as the Next Monday.
Which version of PHP are you using? In some versions of PHP strtotime does have a buggy behavior.
I found that in strtotime manual page:
5.0.2 In PHP 5 up to 5.0.2, "now" and other relative times are wrongly computed from today's midnight. This differs from other versions where it is correctly computed from current time.
5.0.0 Microseconds began to be allowed, but they are ignored.
4.4.0 In PHP versions prior to 4.4.0, "next" is incorrectly computed as +2. A typical solution to this is to use "+1".
Your described behavior suggests that you have a version between 5.0 and 5.0.2.
I suggest you to check whether the difference between today and the computed "next monday" is higher than 7 days. If it is, subtract 7 days and you have the actual date.
Try using that code:
$days = ((strtotime('next monday') - time()) / 60 / 60 / 24);
if ($days >= 8) {
$days -= 7;
}
I know there is date_diff function, but if your PHP version is so low as I think, it isn't available for you (sorry, only 5.3.0 and higher).
"Next", when used with weekdays, generally means the first one after the next closest one. For example if today is Sunday the 21st then the "next" Monday is not tomorrow the 22nd but the following Monday the 29th.
I know this is not necessarily intuitive and not recognized universally but I believe that that is how strtotime() interprets "next".
EDIT: I have confirmed via my own tests that I am incorrect and that "next" should return the first upcoming weekday (the 22nd in my example above). I will leave this answer here unedited as it and the comment below may be helpful to others.
I've some problem with make a simple PHP function to work on my webspace meanwhile it works like expected at my localhost server.
The problem is the following calculation:
echo $Formated = date("Ymd",strtotime("last day of next month"));
This script dosen't seem to work b/c i simply gets the default date 19691231 instead of the correct one 20110630 when running it on my server.
I use windows (XAMP) as my localhost server so i guess there must be some form of problem that lies within the two platforms way of handling it?
strtotime is notoriously problematic going cross-version, so I'd recommend a vast simplification. You can use the 't' character in the date format to represent the last day of the month, then reduce your strtotime call to simply return some timestamp for the next month.
echo $Formated = date("Ymt", strtotime("next month"));
dont use of if month name is not given
try with
date('m/d/y', strtotime('last day next month'));
OR
date('m/d/y', strtotime('last day of march')); // give the month name with of
Reference
Forget Migration and Deployment, in fact strtime is not reliable. Navigate PHP's official site: Check the strtotime manual, especially this comment.
If you have a MySQL connection available, SELECT DATE_ADD( '2011-05-31', INTERVAL 1 MONTH ) would be less redundant since the (correct) functionality is already implemented without you having to implement it yourself.
I really like the PHP function strtotime(), but the user manual doesn't give a complete description of the supported date formats. It only gives a few examples like "10 September 2000", "+1 week 2 days 4 hours 2 seconds", and "next Thursday".
Where can I find a complete description?
I can't find anything official, but I saw a tutorial that says strtotime()
uses GNU Date Input Formats. Those are described in detail in the GNU manual.
One discrepancy I notice is that "next" doesn't match the
behaviour described in the GNU manual. Using strtotime(), "next Thursday" will give you the same result as "Thursday", unless today is a Thursday.
If today is a Thursday, then
strtotime("Thursday") == strtotime("today")
strtotime("next Thursday") == strtotime("today + 7 days")
If today is not a Thursday, then
strtotime("Thursday") == strtotime("next Thursday")
I'm using PHP 5.2.6.
Update:
I guess the user manual has been updated since I posted this, or else I was blind. It now contains a link to the Date and Time Formats chapter, that includes a section on relative formats.
You can start to trace what it is doing by looking at the following C code:
http://cvs.php.net/viewvc.cgi/php-src/ext/date/php_date.c
Search for PHP_FUNCTION(strtotime)
Also this is the main regex parsing:
http://cvs.php.net/viewvc.cgi/php-src/ext/date/lib/parse_date.re
Good luck
In my experience strtotime() can accept anything that even remotely looks like a date. The best way to figure out its boundaries are is to create a test script and plug in values and see what does and doesn't work.
$input = "Apr 10th";
print(date('Y-m-d', strtotime($input)));
Just keep changing the $input variable and observe the results.
Basically anything that date can create strtotime will parse. With one exception, it does have issues with non-US style formatting. So keep it Month-Day-Year type formatting in place.