php convert date to timestamp

Как переводить дату в метку времени в php примеры код скрипт

Как из даты вернуть временную метку, как преобразовать дату во временную метку, способы перегнать дату в timestamp!

Все способы вернуть из даты временную метку

Как преобразовать дату в метку времени! Мы будем сегодня пользоваться функцией strtotime.

Как-то затрагивали тему времени в php и сегодня нам потребовалось дату конвертировать обратно в метку времени(timestamp)!

У есть дата такого формата… запените эту дату вместе с часами и минутами.

Как преобразовать дату во временную метку с помощью strtotime

Результат возврата из даты временную метку:

2019-02-05 11:38 И теперь в качестве функции, которая вернет нам метку времени будем использовать mktime, но сперва нам потребуется, для этой функции, проделать пару манипуляций.

Разобьем с помощью explode в массив:

и сталось вернуть временную метку из даты:

Пропускаем через класс DateTime + присваиваем переменной:

format возвращаем строку даты, преобразованной согласно переданному формату и выводим:

Пропускаем через класс DateTime + присваиваем переменной:

getTimestamp получим метку времени в стиле Unix

Функция date_create создает объект ‘дата’, с которым в дальнейшем можно выполнять некоторые операции.

Пропускаем через функцию date_create + присваиваем переменной:

date_format строку, отформатированную в соответствии с указанным шаблоном format.

1549366680 Либо вместо date_format можно использовать date_timestamp_get

Думаю этих способов вернуть временную метку из даты будет достаточно!

Раз уж выше мы сделали перевод времени в метку времени, то и можно сделать наоборот.

В форме ввода введите метку времени «timestamp», чтобы найти по ней дату.

Сообщение системы комментирования :

Форма пока доступна только админу. скоро все заработает. надеюсь.

Источник

Как преобразовать дату в timestamp в PHP?

ОТВЕТЫ

Ответ 1

Ответ 2

Ответ 3

То же самое с процедурным API:

Если приведенное выше сбой происходит из-за того, что вы используете неподдерживаемый формат, вы можете использовать

Если вы не работаете с локализованными строками даты, более простой выбор, скорее всего, DateTime.

Ответ 4

Действительно, 22-09-2008 будет проанализирован как 22 сентября 2008 года, так как это единственная разумная вещь.

Ответ 5

Если у вас есть PHP 5.3 или выше,

Если вам не нужен часовой пояс или вы хотите использовать часовой пояс, который использует ваш сервер:

1222093324 (Это будет отличаться в зависимости от вашего часового пояса сервера. )

Если вы хотите указать, в каком часовом поясе, здесь EST. (То же, что и в Нью-Йорке.)

1222093305

Или если вы хотите использовать UTC. (То же, что и «GMT».)

1222093289

Ответ 6

Ответ 7

Используя функцию strtotime(), вы можете легко преобразовать дату в метку времени

Ответ 8

Вот очень простое и эффективное решение с использованием функций split и mtime :

Для меня это работало как прелесть.

Ответ 9

Учитывая, что функция strptime() не работает для Windows и strtotime() может возвращать неожиданные результаты, я рекомендую использовать date_parse_from_format() :

Ответ 10

Если вы хотите точно знать, будет ли синтаксическая обработка даты в ожидаемом вами случае, вы можете использовать DateTime::createFromFormat() :

Это очевидно в этом случае, но, например, 03-04-2008 может быть 3 апреля или 4 марта в зависимости от того, откуда вы пришли:)

Ответ 11

Ответ 12

Ответ 13

Ответ 14

Вот как я это сделаю:

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

Ответ 15

Ответ 16

Если вы хотите, поместите его в MySQL тип времени ввода. Вышеупомянутое работает очень хорошо (только на PHP 5 или новее):

Ответ 17

Ответ 18

Используйте функцию PHP strtotime()

Ответ 19

Если вы хотите преобразовать дату и время UTC ( 2016-02-14T12:24:48.321Z ) в метку времени, вот как вы это сделаете:

Источник

Как преобразовать дату в timestamp в PHP?

PHP strtotime() дает

Существует также strptime() который ожидает ровно один формат:

Будьте осторожны с функциями, такими как strtotime() которые пытаются «угадать» то, что вы имеете в виду (это, конечно, не догадывается, правила здесь ).

То же самое с процедурным API:

Еще одна альтернатива – использовать API IntlDateFormatter :

Если вы не работаете с локализованными строками даты, проще выбрать DateTime.

Если у вас PHP 5.3 или выше,

этот метод работает как в Windows, так и в Unix и знает о часовых поясах, что, вероятно, вам нужно, если вы серьезно относитесь к работе с датами.

Если вам не нужен часовой пояс или вы хотите использовать часовой пояс, который использует ваш сервер:

1222093324 (Это будет отличаться в зависимости от вашего часового пояса сервера …)

Если вы хотите указать, в каком часовом поясе, здесь EST. (То же, что и Нью-Йорк.)

1222093305

Или если вы хотите использовать UTC. (То же, что и «GMT».)

1222093289

Это очень простое и эффективное решение с использованием функций split и mtime :

Это работало как прелесть для меня.

Используя функцию strtotime (), вы можете легко преобразовать дату в метку времени

Учитывая, что функция strptime() не работает для Windows, и strtotime() может возвращать неожиданные результаты, я рекомендую использовать date_parse_from_format() :

Если вы хотите точно знать, будет ли синтаксическая обработка даты ожидаемой, вы можете использовать DateTime::createFromFormat() :

Это очевидно в этом случае, но, например, 03-04-2008 может быть 3 апреля или 4 марта в зависимости от того, откуда вы пришли 🙂

Если вы знаете, что формат использует strptime потому что strtotime делает предположение для формата, что может не всегда быть правильным. Поскольку strptime не реализована в Windows, есть пользовательская функция

Помните, что returnvalue tm_year – с 1900 года! и tm_month равно 0-11

Вот как я это сделаю:

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

Если вы хотите преобразовать 2016-02-14T12:24:48.321Z время UTC ( 2016-02-14T12:24:48.321Z ) в метку времени, вот как вы это сделаете:

Источник

strtotime

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

strtotime — Преобразует текстовое представление даты на английском языке в метку времени Unix

Описание

Каждый параметр функции использует временную метку по умолчанию, пока она не указана в этом параметре напрямую. Будьте внимательны и не используйте различные временные метки в параметрах, если на то нет прямой необходимости. Обратите внимание на date_default_timezone_get() для задания часового пояса различными способами.

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

Строка даты/времени. Объяснение корректных форматов дано в разделе Форматы даты и времени.

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

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

Ошибки

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

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

Примеры

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

Пример #2 Проверка ошибок

Примечания

Корректным диапазоном временных меток обычно являются даты с 13 декабря 1901 20:45:54 UTC по 19 января 2038 03:14:07 UTC. (Эти даты соответствуют минимальному и максимальному значению 32-битового знакового целого).

В 64-битных версиях PHP корректный диапазон временных меток фактически бесконечен, так как 64 битов хватит для представления приблизительно 293 миллиарда лет в обоих направлениях.

Чтобы избежать потенциальной неоднозначности, рекомендуется использовать даты в формате стандарта ISO 8601 ( YYYY-MM-DD ), либо пользоваться функцией DateTime::createFromFormat() там, где это возможно.

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

User Contributed Notes 42 notes

I’ve had a little trouble with this function in the past because (as some people have pointed out) you can’t really set a locale for strtotime. If you’re American, you see 11/12/10 and think «12 November, 2010». If you’re Australian (or European), you think it’s 11 December, 2010. If you’re a sysadmin who reads in ISO, it looks like 10th December 2011.

The best way to compensate for this is by modifying your joining characters. Forward slash (/) signifies American M/D/Y formatting, a dash (-) signifies European D-M-Y and a period (.) signifies ISO Y.M.D.

The «+1 month» issue with strtotime
===================================
As noted in several blogs, strtotime() solves the «+1 month» («next month») issue on days that do not exist in the subsequent month differently than other implementations like for example MySQL.

A strtotime também funciona quando concatenamos strings,

UK dates (eg. 27/05/1990) won’t work with strotime, even with timezone properly set.

[red., derick]: What you instead should do is:

WARNING when using «next month», «last month», «+1 month», «-1 month» or any combination of +/-X months. It will give non-intuitive results on Jan 30th and 31st.

The way to get what people would generally be looking for when they say «next month» even on Jan 30 and Jan 31 is to use «first day of next month»:

strtotime() also returns time by year and weeknumber. (I use PHP 5.2.8, PHP 4 does not support it.) Queries can be in two forms:
— «yyyyWww», where yyyy is 4-digit year, W is literal and ww is 2-digit weeknumber. Returns timestamp for first day of week (for me Monday)
— «yyyy-Www-d», where yyyy is 4-digit year, W is literal, ww is 2-digit weeknumber and dd is day of week (1 for Monday, 7 for Sunday)

// Get timestamp of 32nd week in 2009.
strtotime ( ‘2009W32’ ); // returns timestamp for Mon, 03 Aug 2009 00:00:00
// Weeknumbers strtotime ( ‘2009W01’ ); // returns timestamp for Mon, 29 Dec 2008 00:00:00
// strtotime(‘2009W1’); // error! returns false

// See timestamp for Tuesday in 5th week of 2008
strtotime ( ‘2008-W05-2’ ); // returns timestamp for Tue, 29 Jan 2008 00:00:00
?>

Weeknumbers are (probably) computed according to ISO-8601 specification, so doing date(‘W’) on given timestamps should return passed weeknumber.

I tried using sams most popular example but got incorrect results.

Then I read the notes which said:
if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. ***If, however, the year is given in a two digit format and the separator is a dash (-), the date string is parsed as y-m-d.***

I run a theatre’s website. Obviously, I need to ensure shows that have already happened do not appear on web pages, so I use something on the lines of:

So strtotime($end_date) will always return the timestamp at 00:00 that day. If I instead used:

You are not restricted to the same date ranges when running PHP on a 64-bit machine. This is because you are using 64-bit integers instead of 32-bit integers (at least if your OS is smart enough to use 64-bit integers in a 64-bit OS)

The following code will produce difference output in 32 and 64 bit environments.

32-bit PHP: bool(false)
64-bit PHP: int(-30607689600)

This is true for php 5.2.* and 5.3

Also, note that the anything about the year 10000 is not supported. It appears to use only the last digit in the year field. As such, the year 10000 is interpretted as the year 2000; 10086 as 2006, 13867 as 2007, etc

For negative UNIX timestamps, strtotime seems to return the literal you passed in, or it may try to deduct the number of seconds from today’s date.

To work around this behaviour, it appears that the same behaviour as described in the DateTime classes applies:

Specifically this line here (in the EN manual):

Therefore strtotime(‘@-1000’) returns 1000 seconds before the epoch.

It took me a while to notice that strtotime starts searching from just after midnight of the first day of the month. So, if the month starts on the day you search for, the first day of the search is actually the next occurrence of the day.

In my case, when I look for first Tuesday of the current month, I need to include a check to see if the month starts on a Tuesday.

If you want to confront a date stored into mysql as a date field (not a datetime) and a date specified by a literal string, be sure to add «midnight» to the literal string, otherwise they won’t match:

//I.E.: today is 17/02/2011

echo strtotime ( ‘2011-01-01’ ); //1293836400
echo strtotime ( ‘first day of last month’ ); //1293888128 Note: it’s different from the previous one, since it computes also the seconds passed from midnight. So this one is always greater than simple ‘2011-01-01’
echo strtotime ( ‘midnight first day of last monty’ ); //1293836400 Note: it’s the same as ‘2011-01-01’

Apache claims this to be a ‘standard english format’ time. strtotime() feels otherwise.

I came up with this function to assist in parsing this peculiar format.

strtotime is awesome for converting dates.
in this example i will make an RSS date, an
ATOM date, then convert them to a human
readable m/d/Y dates.

[red.: This is a bug, and should be fixed. I have file an issue]

This comment apply to PHP5+

We can now do thing like this with strtotime:
= strtotime ( ‘Monday this week’ );
?>
However this works based on a week starting Sunday. I do not know if we can tweak this PHP behavior, anyone know?

strtotime() will convert a string WITHOUT a timezone indication as if the string is a time in the default timezone ( date_default_timezone_set() ). So converting a UTC time like ‘2018-12-06T09:04:55’ with strtotime() actually yields a wrong result. In this case use:

Adding a note to an already long page:

Try to be as specific as you can with the string you pass in. For example

Assuming today is July 31, the timestamp returned by strtotime(‘February’) will ultimately be seen as February 31 (non-existant obviously), which then is interpreted as March 3, thus giving a month name of March.

Interestingly, adding the year or the day will give you back the expected month.

strtotime() produces different output on 32 and 64 bit systems running PHP 5.3.3 (as mentioned previously). This affects the «zero date» («0000-00-00 00:00:00») as well as dates outside the traditional 32 date range.

In modern 64-bit systems (tested on mac) the old 1970 to 2038 date range limitations are gone.

strtotime(«0001-10-30») gives int(-62109540728)
strtotime(«6788-10-30») gives int(152067506400)

Источник

PHP: Convert a date into a Unix timestamp.

This is a short PHP guide on how to convert a regular date string into a Unix timestamp. As you probably already know, “Unix Time” is the number of seconds that have passed since the 1st of January, 1970.

For the sake of this example, let’s say that we want to convert 2019-04-01 10:32:00 into an Epoch timestamp.

strtotime

To do this in PHP, we can use the strtotime function like so:

If you run the example above, you will see that 1554107520 is printed out onto the page. This is because 1554107520 passed between the Epoch time and 10:32AM on the 1st of April, 2019.

Note that the strtotime function will return a boolean FALSE value if the conversion fails.

Using the DateTime object.

If you prefer using OOP and the DateTime object, then you can do the following:

As you can see, it’s pretty similar to the strtotime approach. In the case above, we simply converted the date by passing the “U” format character into the DateTime “format” method.

Note that if you leave out the exact time, PHP will default to midnight:

The above example will output “1554069600”, which is the Unix timestamp for midnight on the 1st of April, 2019.

By the way, in order to get the current timestamp, you can simply call PHP’s time function like so:

That’s it! Hopefully, you found this guide useful!

Источник

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

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