php string 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», чтобы найти по ней дату.
Сообщение системы комментирования :
Форма пока доступна только админу. скоро все заработает. надеюсь.
strtotime
(PHP 4, PHP 5, PHP 7, PHP 8)
strtotime — Преобразует текстовое представление даты на английском языке в метку времени Unix
Описание
Каждый параметр функции использует временную метку по умолчанию, пока она не указана в этом параметре напрямую. Будьте внимательны и не используйте различные временные метки в параметрах, если на то нет прямой необходимости. Обратите внимание на date_default_timezone_get() для задания часового пояса различными способами.
Список параметров
Строка даты/времени. Объяснение корректных форматов дано в разделе Форматы даты и времени.
Временная метка, используемая в качестве базы для вычисления относительных дат.
Возвращаемые значения
Ошибки
Список изменений
Версия | Описание |
---|---|
8.0.0 | baseTimestamp теперь допускает значение 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!
strtotime — Преобразует текстовое представление даты на английском языке в метку времени Unix
Описание
Каждый параметр функции использует временную метку по умолчанию, пока она не указана в этом параметре напрямую. Будьте внимательны и не используйте различные временные метки в параметрах, если на то нет прямой необходимости. Обратите внимание на date_default_timezone_get() для задания временной зоны различными способами.
Список параметров
Строка даты/времени. Объяснение корректных форматов дано в Форматы даты и времени.
Временная метка, используемая в качестве базы для вычисления относительных дат.
Возвращаемые значения
Ошибки
Список изменений
Примеры
Пример #1 Пример использования функции strtotime()
Пример #2 Проверка ошибок
Примечания
Корректным диапазоном временных меток обычно являются даты с 13 декабря 1901 20:45:54 UTC по 19 января 2038 03:14:07 UTC. (Эти даты соответствуют минимальному и максимальному значению 32-битового знакового целого).
До версии PHP 5.1.0, не все платформы поддерживают отрицательные метки времени, поэтому поддерживаемый диапазон дат может быть ограничен Эпохой Unix. Это означает, что даты ранее 1 января 1970 г. не будут работать в Windows, некоторых дистрибутивах Linux и нескольких других операционных системах.
В 64-битных версиях PHP корректный диапазон временных меток фактически бесконечен, так как 64 битов хватит для представления приблизительно 293 миллиарда лет в обоих направлениях.
Даты в формате m/d/y или d-m-y разрешают неоднозначность с помощью анализа разделителей их элементов: если разделителем является слеш (/), то дата интерпретируется в американском формате m/d/y, если же разделителем является дефис (—) или точка (.), то подразумевается использование европейского форматаd-m-y.
Чтобы избежать потенциальной неоднозначности, рекомендуется использовать даты в формате стандарта ISO 8601 (YYYY-MM-DD) либо пользоваться функцией DateTime::createFromFormat() там, где это возможно.
Не рекомендуется использовать эту функцию для математических операций. Целесообразней использовать DateTime::add() и DateTime::sub() начиная с PHP 5.3, или DateTime::modify() в PHP 5.2.
Смотрите также
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