php datetime minus datetime

DateTime::sub

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

Описание

Список параметров

Возвращаемые значения

Возвращает объект DateTime для применения в цепи методов или false в случае возникновения ошибки.

Примеры

Пример #1 Пример использования DateTime::sub()

Результат выполнения данных примеров:

Пример #2 Другие примеры DateTime::sub()

Результат выполнения данного примера:

Пример #3 Будьте внимательны при вычитании месяцев

= new DateTime ( ‘2001-04-30’ );
$interval = new DateInterval ( ‘P1M’ );

Результат выполнения данного примера:

Смотрите также

User Contributed Notes 6 notes

As noted above when subtracting months, results can be suspect. I needed to create an array of end of month dates for 6 months starting at Oct and going back. Using:
//Instantiate array
$dateset = [];

array:6 [▼
0 => «2018-10-31»
1 => «2018-10-01»
2 => «2018-09-01»
3 => «2018-08-01»
4 => «2018-07-01»
5 => «2018-06-01»
]

array:6 [▼
0 => «2018-10-31»
1 => «2018-09-30»
2 => «2018-08-31»
3 => «2018-07-31»
4 => «2018-06-30»
5 => «2018-05-31»
]

Remark, that calculations on date are not defined as bijective operations. The Summertime is integrated by mixing two concepts. You should test it beforehead.

Datetime will correct a date after each summation, if a date (29.2.2021 => 1.3.2021) or a datetime (29.3.2020 2:30 am (Europe/Berlin) => 29.3.2020 3:30 or 29.3.2020 1:30)

Источник

Date minus 1 year?

I’ve got a date in this format:

How do I return the same date but 1 year earlier?

8 Answers 8

The strtotime function returns a unix timestamp, to get a formatted string you can use date :

Use strtotime() function:

Using the DateTime object.

Or using now for today

an easiest way which i used and worked well

this worked perfect.. hope this will help someone else too.. 🙂

On my website, to check if registering people is 18 years old, I simply used the following :

After, only compare the the two dates.

Hope it could help someone.

Although there are many acceptable answers in response to this question, I don’t see any examples of the sub method using the \Datetime object: https://www.php.net/manual/en/datetime.sub.php

So, for reference, you can also use a \DateInterval to modify a \Datetime object:

You can use the following function to subtract 1 or any years from a date.

And looking at above examples you can also use the following

Not the answer you’re looking for? Browse other questions tagged php date or ask your own question.

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Php datetime minus datetime

Начиная с версии 5.2 в PHP появился такой тип данных как DateTime. Попробуем в этой статье разобраться почему лучше использовать его вместо старых функций date() и time().

Функция time() возвращает текущее время в unix формате (timestamp).

Datetime()

Объект Datetime впервые был представлен в PHP версии 5.2, он содержит в себе множество вспомогательных объектов, для решения проблем, с которыми вам приходилось сталкиваться при использовании функций date() и time(). Также был представлен объект DateTimeZone, который управляет часовым поясом, объект DateInterval соответствует интервалу времени (например 2 дня) от настоящего момента, DatePeriod показывает разницу во времени между двумя разными датами. Основное преимущество использования DateTime перед старыми функциями заключается в том, что значения дат проще изменять. Если вы хотите получить значение времени и даты при помощи функции date(), то вы напишите следующее:

А вот пример для установки часового пояса:

Проблема возникает при необходимости изменить или сравнить две отметки времени, DateTime имеет методы modify() и diff() упрощающие задачу. Преимущества DateTime проявляются когда вы манипулируете значениями дат.

Сначала объект надо инициализировать

Вывод форматированной даты

Объект DateTime может работать также как и функция date, всего лишь необходимо вызвать метод format() указав формат возвращаемой строки.

Вывод отметки времени (timestamp)

Изменение времени

Изменение метки timestamp

Установка часового пояса

Полный список часовых поясов можно просмотреть на php.net.

Как добавить дни к значению даты

Для изменения значения даты в объекте DateTime можно использовать метод modify(). Он принимает в качестве параметра строковое значение дней, месяцев, года. Например, если хотите прибавить несколько дней, например 3 дня, один месяц и один год:

Сравнение двух дат

Код выше даст нам разницу двух дат в виде DateInterval.

Конвертация номера месяца и имени месяца

Довольно часто приходится получать имя месяца из его порядкового номера, для этого всего лишь нужно указать формат “F” в качестве первого параметра

Получаем количество недель в месяце

Следующий пример поможет вам получить количество недель в определенном месяце года.

Источник

How to datenow minus datetime MySQL with PHP in second

i want to minus purchase date with datenow. i have table named count_sec :

example time now is 2015-06-06 08:37:00 what is the code if i am want the code to update the second to:

EDIT i have already create this php, but the code is not work, how to fix?

4 Answers 4

In PHP you can use

But the SQL solution suits this question better.

php datetime minus datetime. Смотреть фото php datetime minus datetime. Смотреть картинку php datetime minus datetime. Картинка про php datetime minus datetime. Фото php datetime minus datetime

Try with the SQL query:

I am not understanding why you need to store this in a column in the table. As soon as it’s stored, the value is old, and it will need to be updated again. (Don’t do this.) But setting that issue aside for a moment.

As to why your code isn’t «working». your UPDATE statement is updating every row in the table. You’ve previously fetched one row from the table, and then calculated one value, and then the UPDATE statement doesn’t have a WHERE clause to identify which row(s) you want to update, so every row gets updated with the same value. That’s a big part of why your code isn’t working.

One convenient way to do that is to use the UNIX_TIMESTAMP function to convert each of the DATETIME values into an integer value (number of seconds), and subtract them. For example:

As an alternative, you could use the TIMESTAMPDIFF function for an equivalent result:

But back to the issue of why this is wrong. You do not want to store second column in the table.

When you run a SELECT statement to return a row from the table, the value in this column is going to old.

Instead, you could just return a calculated value, calculated as of the time the SELECT statement runs, by including one of those expressions in the SELECT list. For example:

The point I’m trying to emphasize here. do not store the second value in the table. You’ll be chasing it, and continuously updating every row in table, whether that’s every five minutes or every five seconds. And the stored value is always going to be «old».

Why do you need that? If you want to find out which rows in the table have second between 60 and 120, for example, if you intend to run this query:

You could just as easily rewrite that based on purchasedate

And, you won’t be «chasing» continuous updates of the rows in the table, generating rollbackup, recording changes in the InnoDB log, writing the UPDATE statements in the binary logs. If you are running replication slaves, those statements have to be read from the log and re-executed on the slaves. All in all, storing second is just a poor design choice.

Источник

Класс DateTime

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

Введение

Обзор классов

Список изменений

Содержание

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 09|[12]6|3[01])» ;
$regexpArray [ ‘-‘ ] = «[-]» ;
$regexpArray [ ‘.’ ] = «[\. /.]» ;
$regexpArray [ ‘:’ ] = «[:]» ;
$regexpArray [ ‘space’ ] = «[\s]» ;
$regexpArray [ ‘H’ ] = «(?P 09|12|23)» ;
$regexpArray [ ‘i’ ] = «(?P25)» ;
$regexpArray [ ‘s’ ] = «(?P11)» ;

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *