php time to datetime

Php time to 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” в качестве первого параметра

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

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

Источник

Дата и время в PHP

В распределенных системах, таких, как Интернет, время играет особую роль. Из-за незначительного расхождения системных часов игрок на рынке Forex может потерять десятки тысяч долларов в течение нескольких минут; система деловой разведки ошибется в составлении прогноза; серверы NNTP в процессе синхронизации потеряют важную информацию, нужную пользователю и т.д.

PHP-функции для работы с датой и временем

PHP содержит множество функций для работы с датой и временем. Наиболее употребимыми являются:

time() Возвращает текущее абсолютное время. Это число равно количеству секунд, которое прошло с полуночи 1 января 1970 года (с начала эпохи UNIX). getdate( ) Считывает информацию о дате и времени. Возвращает ассоциативный массив, содержащий информацию по заданному или по текущему (по умолчанию) времени. Массив содержит следующие элементы:

secondsСекунды (0-59)
minutesМинуты (0-59)
hoursЧасы (0-23)
mdayДень месяца (1-31)
wdayДень недели (0-6), начиная с воскресенья
monМесяц (1-12)
yearГод
ydayДень года (0-365)
weekdayНазвание дня недели (например, Friday)
monthНазвание месяца (например, January)
0Абсолютное время

Пример 1

РЕЗУЛЬТАТ ПРИМЕРА 1:

seconds = 42
minutes = 50
hours = 18
mday = 18
wday = 6
mon = 9
year = 2021
yday = 260
weekday = Saturday
month = September
0 = 1631980242
Сегодня: 18.9.2021

date() Форматирование даты и времени. Аргументы: строка формата и абсолютное время. Второй аргумент необязателен. Возвращает строку с заданной или текущей датой в указанном формате. Строка формата может содержать следующие коды:

Любая другая информация, включенная в строку формата, будет вставлена в возвращаемую строку. Если в строку формата нужно добавить символы, которые сами по себе являются кодами формата, то перед ними надо поставить обратную косую черту «\». Символы, которые становятся кодами формата при добавлении к ним обратной косой, нужно предварять двумя косыми. Например, если необходимо добавить в строку «n», то надо ввести «\\n», поскольку «\n» является символом новой строки.

Пример 2

РЕЗУЛЬТАТ ПРИМЕРА 2:

Сегодня 18.09.21 18:50

часы
минуты
секунды
месяц
день месяца
год

Пример 3

РЕЗУЛЬТАТ ПРИМЕРА 3:

22 January 1971, at 1.30 pm, Friday

Внимание! Дата может находиться в допустимом диапазоне, но остальные функции работы с датами не примут это значение. Так, нельзя использовать mktime() для годов до 1902, а также следует использовать ее осторожно для годов до 1970.

Пример 4

РЕЗУЛЬТАТ ПРИМЕРА 4:

Saturday 18 September 2021 18:50
Сегодня Saturday 18 September 2021 18:50:42
MSK

Источник

Класс 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 03|1[012])» ;
$regexpArray [ ‘d’ ] = «(?P 07|[12]8|3[01])» ;
$regexpArray [ ‘-‘ ] = «[-]» ;
$regexpArray [ ‘.’ ] = «[\. /.]» ;
$regexpArray [ ‘:’ ] = «[:]» ;
$regexpArray [ ‘space’ ] = «[\s]» ;
$regexpArray [ ‘H’ ] = «(?P 07|14|21)» ;
$regexpArray [ ‘i’ ] = «(?P44)» ;
$regexpArray [ ‘s’ ] = «(?P53)» ;

Источник

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

Источник

PHP | Дата и время

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

Функция PHP date()

Функция date() выводит текущие дату и время в заданном формате. Также функция может конвертировать формат отметки времени (временная метка, метка времени или timestamp) в удобочитаемый формат.

Синтаксис

Параметры функции date():

Примечание: Отметка времени — это последовательность символов, обозначающая дату и / или время, когда произошло определенное событие.

Обязательный параметр format функции date() указывает, как форматировать дату (или время). Формат задается управляющими командами (латиницей), при этом можно вставлять любые разделители между ними (дефисы, двоеточие и так далее).

Ниже представлена таблица с расшифровкой некоторых символов в строке format :

Символ в строке formatОписаниеПример возвращаемого значения
День
dДень месяца с 2-мя цифрамиот 01 до 31
DДень недели в текстовом формате, 3 символаот Mon до Sun
zПорядковый номер дня в году (начиная с 0)От 0 до 365
Месяц
FПолное название месяца, например, January или Marchот January до December
mПорядковый номер месяца, 2 цифрыот 01 до 12
MСокращенное название месяца, 3 символаот Jan до Dec
Год
YПорядковый номер года, 4 цифрыПримеры: 1999, 2019
yПорядковый номер года, 2 цифрыПримеры: 99, 19
Время
aAnte meridiem (лат. «до полудня») или Post meridiem (лат. «после полудня») в нижнем регистреam или pm
AAnte meridiem или Post meridiem в верхнем регистреAM или PM
gЧасы в 12-часовом форматеот 1 до 12
GЧасы в 24-часовом форматеот 0 до 23
hЧасы в 12-часовом форматеот 01 до 12
HЧасы в 24-часовом формате, 2 цифрыот 00 до 23
iМинуты, 2 цифрыот 00 до 59
sСекунды, 2 цифрыот 00 до 59

Ниже представлены некоторые примеры получения фактической информации о дате и времени:

Источник

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

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