php datetime diff in minutes
DateTime::diff
DateTimeInterface::diff
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
Описание
Список параметров
Дата и время для сравнения.
Используется, чтобы вернуть абсолютную разницу.
Возвращаемые значения
DateInterval объект представляет разницу между двумя датами или false в случае возникновения ошибки.
Примеры
Пример #1 Пример использования DateTime::diff()
Результат выполнения данных примеров:
Пример #2 Сравнение объектов DateTime
Объекты DateTime могут сравниваться при помощи операторов сравнения.
= new DateTime ( «now» );
$date2 = new DateTime ( «tomorrow» );
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 30 notes
It is worth noting, IMO, and it is implied in the docs but not explicitly stated, that the object on which diff is called is subtracted from the object that is passed to diff.
$date1 = new DateTime(‘now’);
$date2 = new DateTime(‘tomorrow’);
In some situations, this won’t say «in 1 days», but «in 0 days».
I think this is because «now» is the current time, while «tomorrow» is the current day +1 but at a default time, lets say:
Now: 08:00pm, 01.01.2015
Tomorrow: 00:00am, 02.01.2015
In this case, the difference is not 24 hour, so it will says 0 days.
Better use «today», which should also use a default value like:
Today: 00:00am, 01.01.2015
Tomorrow: 00:00am, 02.01.2015
which now is 24 hour and represents 1 day.
This may sound logical and many will say «of course, this is right», but if you use it in a naiv way (like I did without thinking), you can come to this moment and facepalm yourself.
Conclusion: «Now» is «Today», but in a different clock time, but still the same day!
After wrestling with DateTime::diff for a while it finally dawned on me the problem was both in the formatting of the input string and the formatting of the output.
The task was to calculate the duration between two date/times.
1. Make sure you have a valid date variable. Both of these strings are valid:
$strStart = ‘2013-06-19 18:25’ ;
$strEnd = ’06/19/13 21:47′ ;
?>
2. Next convert the string to a date variable
3. Calculate the difference
4. Format the output
[Modified by moderator for clarify]
Using the identical (===) comparision operator in different but equal objects will return false
If you want to quickly scan through the resulting intervals, you can use the undocumented properties of DateInterval.
The function below returns a single number of years, months, days, hours, minutes or seconds between the current date and the provided date. If the date occurs in the past (is negative/inverted), it suffixes it with ‘ago’.
It seems that while DateTime in general does preserve microseconds, DateTime::diff doesn’t appear to account for it when comparing.
= ‘2014-03-18 10:34:09.939’ ;
$val2 = ‘2014-03-18 10:34:09.940’ ;
To work around this apparent limitation/oversight, you have to additionally compare using DateTime::format.
I needed to get the exact number of days between 2 dates and was relying on the this diff function, but found that I was getting a peculiar result with:
I had to end up using :
Though I found a number of people who ran into the issue of 5.2 and lower not supporting this function, I was unable to find any solid examples to get around it. Therefore I hope this can help some others:
Как вычислить разницу между двумя датами с помощью PHP?
у меня есть две даты в виде:
теперь мне нужно найти разницу между этими двумя в следующей форме:
Как я могу это сделать в PHP?
30 ответов
вы можете использовать strtotime() для преобразования двух дат во время unix, а затем вычислить количество секунд между ними. Из этого довольно легко вычислить различные периоды времени.
Edit: очевидно, что предпочтительный способ сделать это, как описано ниже Юрка. Мой код обычно рекомендуется только если у вас нет PHP 5.3 или лучше.
несмотря на все это, я решил обращаться с жалобами. Если вам действительно нужен точный диапазон, но у вас нет доступа к PHP 5.3, используйте код ниже (он также должен работать в PHP 4). Это прямой порт кода, который PHP использует внутри для расчета диапазонов, за исключением того, что он не учитывает летнее время. Это означает, что он выключен максимум на час, но за исключением этого он должен быть правильным.
Я предлагаю использовать объекты DateTime и DateInterval.
начиная с PHP 5.2.2, объекты DateTime можно сравнивать с помощью операторов сравнения.
лучший курс действий-использование PHP DateTime (и DateInterval ) объекты. Каждая дата инкапсулируется в DateTime объект, а затем разница между ними может быть сделана:
на DateTime объект примет любой формат strtotime() будет. Если требуется еще более конкретный формат даты, DateTime::createFromFormat() можно использовать для создания DateTime объект.
после создания экземпляра обоих объектов вы вычитаете один из другого с помощью DateTime::diff() .
$difference теперь DateInterval объект с информацией разницу. А var_dump() выглядит так:
в формате DateInterval объект, нам нужно проверить каждое значение и исключить его, если это 0:
просмотр часов и минут и секунд..
взгляните на следующую ссылку. Это лучший ответ, который я нашел до сих пор.. 🙂
не имеет значения, какая дата раньше или позже, когда вы проходите в параметры даты. Функция использует абсолютное значение PHP ABS() для всегда возвращайте положительное число как количество дней между двумя даты.
имейте в виду, что количество дней между двумя датами не включительно. Так что, если вы ищете количество дней представлено всеми датами между и включая введенные даты, вам нужно будет добавить один (1) к результату этой функции.
Я голосовал за Юрка ‘ s ответ как это мой любимый, но у меня есть pre-php.5.3 версии.
я получил оригинальную идею от здесь, который я изменил для моего использования (и я надеюсь, что моя модификация будет отображаться на этой странице).
Я не знаю, используете ли вы фреймворк PHP или нет, но многие фреймворки PHP имеют библиотеки даты/времени и помощники, которые помогут вам не изобретать колесо.
Calculate the difference between two dates in PHP.
This is a simple guide on how to calculate the difference between two dates in PHP. Be sure to try out the examples below if you’re new to the topic.
Our dates.
Let us say, for example, that we have two date strings and that they are formatted like so:
As you can see, there’s about a year in the difference between them.
However, what if we want to calculate the exact number of seconds that have passed between date one and date two?
If you run the code above, you’ll see that the answer is: 31490659. i.e. 31490659 seconds passed between “2013-03-01 19:12:45” and “2014-03-01 06:37:04”.
A basic drill down of what I did:
Remember: The older a date is, the smaller its corresponding timestamp will be! Run the following example to see what I mean:
As you can see, “2014-06-07” has a much bigger timestamp, simply because more seconds have passed since the 1st of January, 1971 and the 7th of June, 2014.
Between then and now.
What if you need to find out how many seconds have passed since a given date?
If you continue to refresh the page, you’ll see that the difference in seconds will continue to grow.
Minutes & Days…
In many cases, you’ll want the number of days or minutes that have passed. Let’s face it: Seconds are kind of useless to an end user.
To calculate the number of days that have passed:
As you can see, I was able to convert seconds into days via some basic math:
If you multiply the figures above, it will give you 86400, which is total the number of seconds that is in a given day. Divide the difference in seconds between our two dates by 86400 and you’ve got the number of days that have passed.
You can then use the floor function in order to round the result down. i.e. 2.9 days = 2 days.
To get the number of minutes, you can simply divide the difference in seconds by 60, like so:
As you can see, it’s pretty simple.
Once you’ve grasped the fundamentals of dealing with dates and timestamps in PHP, you should look into using the DateTime class, simply because it’s cleaner and it provides you with an OO interface.
For example, if we want to get the difference in days using the DateTime class, we can do the following:
To transform the difference into a human-readable format that is comprised of years, months, days, hours and minutes:
As you can see, the DateTime class is pretty powerful once you figure out to use it!
The DateTime class
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
Introduction
This class behaves the same as DateTimeImmutable except objects are modified itself when modification methods such as DateTime::modify() are called.
Class synopsis
Changelog
Table of Contents
User Contributed Notes 26 notes
Set Timezone and formatting.
= time ();
$timeZone = new \ DateTimeZone ( ‘Asia/Tokyo’ );
DateTime supports microseconds since 5.2.2. This is mentioned in the documentation for the date function, but bears repeating here. You can create a DateTime with fractional seconds and retrieve that value using the ‘u’ format string.
// Instantiate a DateTime with microseconds.
$d = new DateTime ( ‘2011-01-01T15:03:01.012345Z’ );
There is a subtle difference between the following two statments which causes JavaScript’s Date object on iPhones to fail.
/**
On my local machine this results in:
Both of these strings are valid ISO8601 datetime strings, but the latter is not accepted by the constructor of JavaScript’s date object on iPhone. (Possibly other browsers as well)
*/
?>
Our solution was to create the following constant on our DateHelper object.
class DateHelper
<
/**
* An ISO8601 format string for PHP’s date functions that’s compatible with JavaScript’s Date’s constructor method
* Example: 2013-04-12T16:40:00-04:00
*
* PHP’s ISO8601 constant doesn’t add the colon to the timezone offset which is required for iPhone
**/
const ISO8601 = ‘Y-m-d\TH:i:sP’ ;
>
?>
Small but powerful extension to DateTime
class Blar_DateTime extends DateTime <
= new Blar_DateTime ( ‘1879-03-14’ );
Albert Einstein would now be 130 years old.
Albert Einstein would now be 130 Years, 10 Months, 10 Days old.
Albert Einstein was on 2010-10-10 131 years old.
Example displaying each time format:
$dateTime = new DateTime();
The above example will output:
At PHP 7.1 the DateTime constructor incorporates microseconds when constructed from the current time. Make your comparisons carefully, since two DateTime objects constructed one after another are now more likely to have different values.
This caused some confusion with a blog I was working on and just wanted to make other people aware of this. If you use createFromFormat to turn a date into a timestamp it will include the current time. For example:
if you’d like to print all the built-in formats,
This might be unexpected behavior:
#or use the interval
#$date1->add(new DateInterval(«P1M»));
#will produce 2017-10-1
#not 2017-09-30
A good way I did to work with millisecond is transforming the time in milliseconds.
function timeToMilliseconds($time) <
$dateTime = new DateTime($time);
If you have timezone information in the time string you construct the DateTime object with, you cannot add an extra timezone in the constructor. It will ignore the timezone information in the time string:
$date = new DateTime(«2010-07-05T06:00:00Z», new DateTimeZone(«Europe/Amsterdam»));
will create a DateTime object set to «2010-07-05 06:00:00+0200» (+2 being the TZ offset for Europe/Amsterdam)
To get this done, you will need to set the timezone separately:
$date = new DateTime(«2010-07-05T06:00:00Z»);
$date->setTimeZone(new DateTimeZone(«Europe/Amsterdam»);
This will create a DateTime object set to «2010-07-05 08:00:00+0200»
It isn’t obvious from the above, but you can insert a letter of the alphabet directly into the date string by escaping it with a backslash in the format string. Note that if you are using «double» speech marks around the format string, you will have to further escape each backslash with another backslash! If you are using ‘single’ speech marks around the format string, then you only need one backslash.
For instance, to create a string like «Y2014M01D29T1633», you *could* use string concatenation like so:
please note that using
setTimezone
setTimestamp
setDate
setTime
etc..
$original = new DateTime(«now»);
so a datetime object is mutable
(Editors note: PHP 5.5 adds DateTimeImmutable which does not modify the original object, instead creating a new instance.)
Create function to convert GregorianDate to JulianDayCount
Note that the ISO8601 constant will not correctly parse all possible ISO8601 compliant formats, as it does not support fractional seconds. If you need to be strictly compliant to that standard you will have to write your own format.
Bug report #51950 has unfortunately be closed as «not a bug» even though it’s a clear violation of the ISO8601 standard.
It seems like, due to changes in the DateTimeZone class in PHP 5.5, when creating a date and specifying the timezone as a a string like ‘EDT’, then getting the timezone from the date object and trying to use that to set the timezone on a date object you will have problems but never know it. Take the following code:
Be aware that DateTime may ignore fractional seconds for some formats, but not when using the ISO 8601 time format, as documented by this bug:
$dateTime = DateTime::createFromFormat(
DateTime::ISO8601,
‘2009-04-16T12:07:23.596Z’
);
// bool(false)
Be aware of this behaviour:
In my opinion, the former date should be adjusted to 2014/11/30, that is, the last day in the previous month.
Here is easiest way to find the days difference between two dates:
If you’re stuck on a PHP 5.1 system (unfortunately one of my clients is on a rather horrible webhost who claims they cannot upgrade php) you can use this as a quick workaround:
If you need DateTime::createFromFormat functionality in versions class DateClass extends DateTime <
<>
$regexpArray [ ‘Y’ ] = «(?P 19|20\d\d)» ;
$regexpArray [ ‘m’ ] = «(?P 08|1[012])» ;
$regexpArray [ ‘d’ ] = «(?P 02|[12]5|3[01])» ;
$regexpArray [ ‘-‘ ] = «[-]» ;
$regexpArray [ ‘.’ ] = «[\. /.]» ;
$regexpArray [ ‘:’ ] = «[:]» ;
$regexpArray [ ‘space’ ] = «[\s]» ;
$regexpArray [ ‘H’ ] = «(?P 07|15|21)» ;
$regexpArray [ ‘i’ ] = «(?P37)» ;
$regexpArray [ ‘s’ ] = «(?P31)» ;
Adding minutes to date time in PHP
I’m really stuck with adding X minutes to a datetime, after doing lots of google’ing and PHP manual reading, I don’t seem to be getting anywhere.
The date time format I have is:
2011-11-17 05:05 : year-month-day hour:minute
Minutes to add will just be a number between 0 and 59
I would like the output to be the same as the input format with the minutes added.
Could someone give me a working code example, as my attempts don’t seem to be getting me anywhere?
13 Answers 13
The ISO 8601 standard for duration is a string in the form of PS where the <*>parts are replaced by a number value indicating how long the duration is.
For example, P1Y2DT5S means 1 year, 2 days, and 5 seconds.
In the example above, we are providing PT5M (or 5 minutes) to the DateInterval constructor.
PHP’s DateTime class has a useful modify method which takes in easy-to-understand text.
You could also use string interpolation or concatenation to parameterize it:
If you are no familiar with strtotime yet, you better head to php.net to discover it’s great power 🙂
You can do this with native functions easily:
I’d recommend the DateTime class method though, just posted by Tim.
I don’t know why the approach set as solution didn’t work for me. So I’m posting here what worked for me in hope it can help anybody:
I thought this would help some when dealing with time zones too. My modified solution is based off of @Tim Cooper’s solution, the correct answer above.
The bold line, line 3, is the addition. I hope this helps some folks as well.
A bit of a late answer, but the method I would use is:
If you want to give a variable that contains the minutes.
Then I think this is a great way to achieve this.
As noted by Brad and Nemoden in their answers above, strtotime() is a great function. Personally, I found the standard DateTime Object to be overly complicated for many use cases. I just wanted to add 5 minutes to the current time, for example.
I wrote a function that returns a date as a string with some optional parameters:
1.) time:String | ex: «+5 minutes» (default = current time)
2.) format:String | ex: «Y-m-d H:i:s» (default = «Y-m-d H:i:s O»)
Obviously, this is not a fully featured method. Just a quick and simple function for modifying/formatting the current date.