php datetime 1 year

Php datetime 1 year

Начиная с версии 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” в качестве первого параметра

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

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

Источник

Класс 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 01|1[012])» ;
$regexpArray [ ‘d’ ] = «(?P 07|[12]9|3[01])» ;
$regexpArray [ ‘-‘ ] = «[-]» ;
$regexpArray [ ‘.’ ] = «[\. /.]» ;
$regexpArray [ ‘:’ ] = «[:]» ;
$regexpArray [ ‘space’ ] = «[\s]» ;
$regexpArray [ ‘H’ ] = «(?P 09|17|23)» ;
$regexpArray [ ‘i’ ] = «(?P24)» ;
$regexpArray [ ‘s’ ] = «(?P52)» ;

Источник

add one year to datetime with php

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

6 Answers 6

strtotime() is the function you’re looking for:

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

First, you have to convert the MySQL datetime to something that PHP can understand. There are two ways of doing this.

Use UNIX_TIMESTAMP() in your query to tell MySQL to return a UNIX timestamp of the datetime column.

Use DateTime::createFromFormat to convert your string time to something PHP can understand.

Once that is done, you can work with the time. Depending on the method you used above, you can use one of the following.

If you have a unix timestamp, you can use the following to add a year:

If you have a DateTime object, you can use the following:

Now, to display your date in a format that is respectable, you must tell PHP to return a string in the proper format.

If you have a unix timestamp, you can use the following:

If you have a DateTime object, you can use the following:

Alternatively, if you don’t want to deal with all of that, you can simply add one year when you query.

Current (2017) Practice is to use DateTime

This question is top on a google search for «php datetime add one year», but severely outdated. While most of the previous answers will work fine for most cases, the established standard is to use DateTime objects for this instead, primarily due strtotime requiring careful manipulation of timezones and DST.

Following this pattern for manipulating dates and times will handle the worst oddities of timezone/DST/leap-time for you.

Just remember two final notes:

Источник

Php datetime 1 year

(PHP 4, PHP 5, PHP 7, PHP 8)

date — Форматирует вывод системной даты/времени

Описание

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

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

Ошибки

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

ВерсияОписание
8.0.0timestamp теперь допускает значение null.

Примеры

Пример #1 Примеры использования функции date()

// установка часового пояса по умолчанию.
date_default_timezone_set ( ‘UTC’ );

// выведет примерно следующее: Monday
echo date ( «l» );

// выведет примерно следующее: Monday 8th of August 2005 03:12:46 PM
echo date ( ‘l jS \of F Y h:i:s A’ );

/* пример использования константы в качестве форматирующего параметра */
// выведет примерно следующее: Mon, 15 Aug 2005 15:12:46 UTC
echo date ( DATE_RFC822 );

Чтобы запретить распознавание символа как форматирующего, следует экранировать его с помощью обратного слеша. Если экранированный символ также является форматирующей последовательностью, то следует экранировать его повторно.

Пример #2 Экранирование символов в функции date()

Пример #3 Пример совместного использования функций date() и mktime()

Данный способ более надёжен, чем простое вычитание и прибавление секунд к метке времени, поскольку позволяет при необходимости гибко осуществить переход на летнее/зимнее время.

Пример #4 Форматирование с использованием date()

// Предположим, что текущей датой является 10 марта 2001, 5:16:18 вечера,
// и мы находимся в часовом поясе Mountain Standard Time (MST)

$today = date ( «F j, Y, g:i a» ); // March 10, 2001, 5:16 pm
$today = date ( «m.d.y» ); // 03.10.01
$today = date ( «j, n, Y» ); // 10, 3, 2001
$today = date ( «Ymd» ); // 20010310
$today = date ( ‘h-i-s, j-m-y, it is w Day’ ); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date ( ‘\i\t \i\s \t\h\e jS \d\a\y.’ ); // it is the 10th day.
$today = date ( «D M j G:i:s T Y» ); // Sat Mar 10 17:16:18 MST 2001
$today = date ( ‘H:m:s \m \i\s\ \m\o\n\t\h’ ); // 17:03:18 m is month
$today = date ( «H:i:s» ); // 17:16:18
$today = date ( «Y-m-d H:i:s» ); // 2001-03-10 17:16:18 (формат MySQL DATETIME)
?>

Примечания

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

User Contributed Notes 20 notes

Things to be aware of when using week numbers with years.

Conclusion:
if using ‘W’ for the week number use ‘o’ for the year.

In order to define leap year you must considre not only that year can be divide by 4!

The correct alghoritm is:

if (year is not divisible by 4) then (it is a common year)
else if (year is not divisible by 100) then (it is a leap year)
else if (year is not divisible by 400) then (it is a common year)
else (it is a leap year)

So the code should look like this:

For Microseconds, we can get by following:

echo date(‘Ymd His’.substr((string)microtime(), 1, 8).’ e’);

FYI: there’s a list of constants with predefined formats on the DateTime object, for example instead of outputting ISO 8601 dates with:

echo date ( ‘Y-m-d\TH:i:sO’ );
?>

You can use

echo date ( DateTime :: ISO8601 );
?>

instead, which is much easier to read.

this how you make an HTML5 tag correctly

It’s common for us to overthink the complexity of date/time calculations and underthink the power and flexibility of PHP’s built-in functions. Consider http://php.net/manual/en/function.date.php#108613

date() will format a time-zone agnostic timestamp according to the default timezone set with date_default_timezone_set(. ). Local time. If you want to output as UTC time use:

$tz = date_default_timezone_get ();
date_default_timezone_set ( ‘UTC’ );

For HTML5 datetime-local HTML input controls (http://www.w3.org/TR/html-markup/input.datetime-local.html) use format example: 1996-12-19T16:39:57

To generate this, escape the ‘T’, as shown below:

If timestamp is a string, date converts it to an integer in a possibly unexpected way:

The example below formats today’s date in three different ways:

The following function will return the date (on the Gregorian calendar) for Orthodox Easter (Pascha). Note that incorrect results will be returned for years less than 1601 or greater than 2399. This is because the Julian calendar (from which the Easter date is calculated) deviates from the Gregorian by one day for each century-year that is NOT a leap-year, i.e. the century is divisible by 4 but not by 10. (In the old Julian reckoning, EVERY 4th year was a leap-year.)

This algorithm was first proposed by the mathematician/physicist Gauss. Its complexity derives from the fact that the calculation is based on a combination of solar and lunar calendars.

At least in PHP 5.5.38 date(‘j.n.Y’, 2222222222) gives a result of 2.6.2040.

So date is not longer limited to the minimum and maximum values for a 32-bit signed integer as timestamp.

Prior to PHP 5.6.23, Relative Formats for the start of the week aligned with PHP’s (0=Sunday,6=Saturday). Since 5.6.23, Relative Formats for the start of the week align with ISO-8601 (1=Monday,7=Sunday). (http://php.net/manual/en/datetime.formats.relative.php)

This can produce different, and seemingly incorrect, results depending on your PHP version and your choice of ‘w’ or ‘N’ for the Numeric representation of the day of the week:

Prior to PHP 5.6.23, this results in:

Today is Sun 2 Oct 2016, day 0 of this week. Day 1 of next week is 10 Oct 2016
Today is Sun 2 Oct 2016, day 7 of this week. Day 1 of next week is 10 Oct 2016

Since PHP 5.6.23, this results in:

Today is Sun 2 Oct 2016, day 0 of this week. Day 1 of next week is 03 Oct 2016
Today is Sun 2 Oct 2016, day 7 of this week. Day 1 of next week is 03 Oct 2016

I’ve tested it pretty strenuously but date arithmetic is complicated and there’s always the possibility I missed something, so please feel free to check my math.

The function could certainly be made much more powerful, to allow you to set different days to be ignored (e.g. «skip all Fridays and Saturdays but include Sundays») or to set up dates that should always be skipped (e.g. «skip July 4th in any year, skip the first Monday in September in any year»). But that’s a project for another time.

$start = strtotime ( «1 January 2010» );
$end = strtotime ( «13 December 2010» );

// Add as many holidays as desired.
$holidays = array();
$holidays [] = «4 July 2010» ; // Falls on a Sunday; doesn’t affect count
$holidays [] = «6 September 2010» ; // Falls on a Monday; reduces count by one

?>

Or, if you just want to know how many work days there are in any given year, here’s a quick function for that one:

Источник

Работа с датой и временем в PHP в ООП стиле. Часть 1

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

Перед web-разработчиками часто возникают задачи, в которых они должны работать с датой и временем. Если вы все еще используете PHP функции, такие как strtotime и date для работы с датой и временем в PHP, то вы многое упускаете.

PHP предоставляет специализированный класс DateTime для работы с датой и временем. Однако, многие игнорируют его использование, несмотря на то, что он доступен в PHP начиная с версии 5.2.

Вот несколько причин, почему предпочтительнее использовать класс DateTime вместо strtotime и date:

Создание объекта класса DateTime.

Создание объекта класса DateTime ничем не отличается от создания экземпляра какого-либо другого класса в PHP.

Если в конструктор класса DateTime не передавать параметр, то будет создан объект с текущей временной меткой и временной зоной по умолчанию. Временная зона в PHP, как правило, настраивается в файле php.ini. Вот так создается объект DateTime с текущим временем.

При необходимости мы можем передать в конструктор класса DateTime строку, представляющую собой правильную дату и время. В качестве временной зоны будет использована та, что установлена по умолчанию.

Несколько примеров создания объекта DateTime с передачей в конструктор строки, содержащей время.

$yesterday = new DateTime(‘yesterday’); // вчера
$twoDaysLater = new DateTime(‘+ 2 days’); // на 2 дня вперед
$oneWeekEarly = new DateTime(‘- 1 week’); // минус одна неделя

Второй параметр конструктора класса DateTime позволяет определить временную зону. Этот параметр имеет тип DateTimeZone.

Например, чтобы создать объект класса DateTime с временной зоной Москвы надо сделать следующее:

$yesterdayInMoscow = new DateTime(‘yesterday’, new DateTimeZone(‘Moscow’));

Конечно, мы также можем создать объект DateTime как обычно, с помощью строки.

$dateTime = new DateTime(‘2015-01-01 12:30:12’);

Формат

В зависимости от системы, которую мы собираемся проектировать, нам могут понадобится различные форматы даты и времени. Форматирование объекта DateTime в формат необходимый в конкретном проекте достаточно просто делается через метод DateTime::format().

Метод DateTime::format() принимает в качестве параметра строку. Эта строка может включать плейсхолдеры, перечисленные на странице официальной документации PHP.

Например, чтобы получить подобный формат YYYY-dd-mm, где Y – год, d – день, m – месяц необходимо сделать следующее:

Мы можем создать любой желаемый формат даты. Вот несколько дополнительных опций:

print_r($now->format(‘jS F Y’));
print_r($now->format(‘ga jS M Y’));
print_r($now->format(‘Y/m/d s:i:H’));

Сравнение дат и времени

Для того, чтобы сравнить две даты с помощью встроенной в PHP функции strtotime, нам сначала нужно преобразовать строковое содержимое этих дат в их эквиваленты временных меток.

В отличие же, от данной функции, объект DateTime предоставляет возможность сравнивать два объекта DateTime как два обычных числа. Вот несколько примеров:

$today = new DateTime(‘today’);
$yesterday = new DateTime(‘yesterday’);

Но бывают случаи, когда логическое значение от сравнения двух дат недостаточно. Например, нам нужно знать, точную разницу между двумя датами. И DateTime::diff() является тем методом, который поможет нам узнать разницу между двумя объектами DateTime. Этот метод возвращает объект класса DateInterval, который может быть использован для получения интервала, в любом требуемом нами формате посредством метода DateInterval::format.

Например, для получения количества дней между сегодняшней датой и вчерашней датой, мы можем сделать следующее:

Со всем разнообразием свойств класса DateInterval вы можете ознакомиться на официальном сайте PHP.

На этом все, и в следующей статье мы продолжим изучать классы для работы с датой и временем в PHP.

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

Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления

Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

Порекомендуйте эту статью друзьям:

Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

Комментарии ( 3 ):

Всем привет извините что пишу здесь но е могли бы подсказать хотел бы узнать как сделать так что бы ретрансляцию для моего сайта хочу чтобы например телеканал тнт транслировалась прямо с моего сайта а не сервера тнт.. Вот этот сайт введет трансляцию мачт тв с своего сервера http://fifa.beta.tj/schedule

Уточните, пожалуйста, вы хотите чтобы, когда пользователь заходил к Вам на сайт, то он мог бы смотреть передачу на вашем сайте?

Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

Copyright © 2010-2021 Русаков Михаил Юрьевич. Все права защищены.

Источник

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

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