php new datetime now
Php new datetime now
Начиная с версии 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” в качестве первого параметра
Получаем количество недель в месяце
Следующий пример поможет вам получить количество недель в определенном месяце года.
Date/Time Functions
Table of Contents
User Contributed Notes 25 notes
I ran into an issue using a function that loops through an array of dates where the keys to the array are the Unix timestamp for midnight for each date. The loop starts at the first timestamp, then incremented by adding 86400 seconds (ie. 60 x 60 x 24). However, Daylight Saving Time threw off the accuracy of this loop, since certain days have a duration other than 86400 seconds. I worked around it by adding a couple of lines to force the timestamp to midnight at each interval.
When debugging code that stores date/time values in a database, you may find yourself wanting to know the date/time that corresponds to a given unix timestamp, or the timestamp for a given date & time.
The following script will do the conversion either way. If you give it a numeric timestamp, it will display the corresponding date and time. If you give it a date and time (in almost any standard format), it will display the timestamp.
All conversions are done for your locale/time zone.
For those who are using pre MYSQL 4.1.1, you can use:
TO_DAYS([Date Value 1])-TO_DAYS([Date Value 2])
For the same result as:
DATEDIFF([Date Value 1],[Date Value 2])
This dateDiff() function can take in just about any timestamp, including UNIX timestamps and anything that is accepted by strtotime(). It returns an array with the ability to split the result a couple different ways. I built this function to suffice any datediff needs I had. Hope it helps others too.
I needed a function that determined the last Sunday of the month. Since it’s made for the website’s «next meeting» announcement, it goes based on the system clock; also, if today is between Sunday and the end of the month, it figures out the last Sunday of *next* month. lastsunday() takes no arguments and returns the date as a string in the form «January 26, 2003». I could probably have streamlined this quite a bit, but at least it’s transparent code. =)
/* The two functions calculate when the next meeting will
be, based on the assumption that the meeting will be on
the last Sunday of the month. */
I wanted to find all records in my database which match the current week (for a call-back function). I made up this function to find the start and end of the current week :
Not really elegant, but tells you, if your installed timezonedb is the most recent:
Someone may find this info of some use:
Rules for calculating a leap year:
1) If the year divides by 4, it is a leap year (1988, 1992, 1996 are leap years)
2) Unless it divides by 100, in which case it isn’t (1900 divides by 4, but was not a leap year)
3) Unless it divides by 400, in which case it is actually a leap year afterall (So 2000 was a leap year).
In practical terms, to work out the number of days in X years, multiply X by 365.2425, rounding DOWN to the last whole number, should give you the number of days.
The result will never be more than one whole day inaccurate, as opposed to multiplying by 365, which, over more years, will create a larger and larger deficit.
I needed to calculate the week number from a given date and vice versa, where the week starts with a Monday and the first week of a year may begin the year before, if the year begins in the middle of the week (Tue-Sun). This is the way weekly magazines calculate their issue numbers.
Here are two functions that do exactly that:
Hope somebody finds this useful.
Use the mySQL UNIX_TIMESTAMP() function in your SQL definition string. i.e.
$sql= «SELECT field1, field2, UNIX_TIMESTAMP(field3) as your_date
FROM your_table
WHERE field1 = ‘$value'»;
The query will return a temp table with coulms «field1» «Field2» «your_date»
The «your_date» will be formatted in a UNIX TIMESTAMP! Now you can use the PHP date() function to spew out nice date formats.
Hope this helps someone out there!
//function like dateDiff Microsoft
//not error in year Bissesto
Класс 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 04|1[012])» ;
$regexpArray [ ‘d’ ] = «(?P 07|[12]9|3[01])» ;
$regexpArray [ ‘-‘ ] = «[-]» ;
$regexpArray [ ‘.’ ] = «[\. /.]» ;
$regexpArray [ ‘:’ ] = «[:]» ;
$regexpArray [ ‘space’ ] = «[\s]» ;
$regexpArray [ ‘H’ ] = «(?P 07|14|23)» ;
$regexpArray [ ‘i’ ] = «(?P49)» ;
$regexpArray [ ‘s’ ] = «(?P24)» ;
Работа с датой и временем в PHP в ООП стиле. Часть 1
Перед 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.
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
Комментарии ( 3 ):
Всем привет извините что пишу здесь но е могли бы подсказать хотел бы узнать как сделать так что бы ретрансляцию для моего сайта хочу чтобы например телеканал тнт транслировалась прямо с моего сайта а не сервера тнт.. Вот этот сайт введет трансляцию мачт тв с своего сервера http://fifa.beta.tj/schedule
Уточните, пожалуйста, вы хотите чтобы, когда пользователь заходил к Вам на сайт, то он мог бы смотреть передачу на вашем сайте?
Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.
Copyright © 2010-2021 Русаков Михаил Юрьевич. Все права защищены.
NOW() function in PHP
For example, to return:
20 Answers 20
You can use the date function:
800 upvotes more. Your answer submission was probably seconds apart from his. 🙂 Thank You for writing it anyways 😀
With PHP version >= 5.4 DateTime can do this:-
Short answer
Read below for the long answer.
The mimicry of the MySQL NOW() function in PHP
Here is a list of ways in PHP that mimic the MySQL NOW() function.
I think that date_create()->format(‘Y-m-d H:i:s’) is the best way because this approach allows you to handle time/time-zone manipulations easier than date(‘Y-m-d H:i:s’) and it works since php 5.2.
MySQL NOW() function
The variables up here are read-only variables. So you can’t change it.
I guess the MySQL NOW() function gets it’s format from the datetime_format variable.
The advantages of date_create()->format() instead date() summary
The favorable facts of date_create(‘now’)->format(‘Y-m-d H:i:s’) over date(‘Y-m-d H:i:s’) are:
The disadvantages of date_create()->format() instead date()
The upper case shows that date() is faster. However, if we change the test scenario a bit, then outcome will be different. See below:
The advantages of date_create()->format() instead date() detailed
Read on for the detailed explanation.
easier to handle time manipulations
date() accepts a relative date/time format as well, like this:
easier to handle timezones
It is possible to change the timezone during run-time. Example:
O.O.P. uses state-full Objects. So I prefer to think in this way:
Then to think in this way:
date_create() VS new DateTime()
The favorable facts of date_create() over new DateTime() are:
Namespaces
If you work in a namespace and want to initialise a DateTime object with the new keyword, then you have to do it like this:
There is nothing wrong with this, but the downside of the above is that people forget sporadically about the backslash. By using the date_create() constructor function you don’t have to worry about namespaces.
Example of date_create()->format()
I use this approach for my projects if I have to fill an array. Like this: