php convert time to time
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
При работе с датой и временем в PHP часто встает задача конвертирования даты и времени из одного формата в другой. В данном скрипте я покажу вам несколько способов, как можно конвертировать дату и время в PHP.
// самый простой способ получения человеко читаемой даты
echo date(‘m/d/Y’,1319446702)
// а здесь получаем дату и время
echo date(‘m/d/Y H:i:s’,1319446702);
// вариант с использованием ООП
$timestamp = 1319446702;
$datetimeFormat = ‘Y-m-d H:i:s’;
$date = new \DateTime();
А вот более изощренный способ конвертирования временной метки в PHP в человекочитаемый формат:
А вот еще один пример с ООП:
Ну вот, пожалуй, этого будет достаточно для большинства ситуаций в PHP, где необходимо конвертировать временную метку unix (unix timestamp) в понятную человеку информацию.
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
Комментарии ( 0 ):
Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.
Copyright © 2010-2021 Русаков Михаил Юрьевич. Все права защищены.
How to convert the time from AM/PM to 24 hour format in PHP?
For example, I have a time in this format:
How do I convert it to :
Currently my code is :
However, it seems there are some easier and more elegant way to do this?
How do I fit the above sample in my case? Thanks.
8 Answers 8
or you can try like this also
You can use this for 24 hour to 12 hour:
And for vice versa:
Works great when formatting date is required. Check This Answer for details.
Not the answer you’re looking for? Browse other questions tagged php string date or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Php convert time to time
(PHP 4, PHP 5, PHP 7, PHP 8)
time — Возвращает текущую метку системного времени Unix
Описание
Возвращает количество секунд, прошедших с начала эпохи Unix (1 января 1970 00:00:00 GMT) до текущего времени.
Список параметров
У этой функции нет параметров.
Возвращаемые значения
Возвращает текущую метку системного времени.
Примеры
Пример #1 Пример использования time()
Результатом выполнения данного примера будет что-то подобное:
Примечания
Смотрите также
User Contributed Notes 21 notes
The documentation should have this info. The function time() returns always timestamp that is timezone independent (=UTC).
Two quick approaches to getting the time elapsed in human readable form.
$nowtime = time ();
$oldtime = 1335939007 ;
/** Output:
time_elapsed_A: 6d 15h 48m 19s
time_elapsed_B: 6 days 15 hours 48 minutes and 19 seconds ago.
**/
?>
A time difference function that outputs the time passed in facebook’s style: 1 day ago, or 4 months ago. I took andrew dot macrobert at gmail dot com function and tweaked it a bit. On a strict enviroment it was throwing errors, plus I needed it to calculate the difference in time between a past date and a future date.
Argument order (begin date, end date) doesn’t matter.
I needed to convert between Unix timestamps and Windows/AD timestamps, so I wrote a pair of simple functions for it.
Below, a function to create TNG-style stardates, taking 2009 to start stardate 41000.0. In fact, the offset is trivial to adjust if you wish to begin from a different date.
Here’s a snippet of code that demonstrates the difference:
// Find the next second
$nextSecond = time () + 1 ;
// TIME: 1525735820 uTIME: 1525735820.997716
// TIME: 1525735820 uTIME: 1525735820.998137
// TIME: 1525735820 uTIME: 1525735820.998528
// TIME: 1525735820 uTIME: 1525735820.998914
// TIME: 1525735820 uTIME: 1525735820.999287
// TIME: 1525735820 uTIME: 1525735820.999657
// TIME: 1525735820 uTIME: 1525735821.000026 time() is behind
// TIME: 1525735820 uTIME: 1525735821.000367 time() is behind
// TIME: 1525735820 uTIME: 1525735821.000705 time() is behind
// TIME: 1525735820 uTIME: 1525735821.001042 time() is behind
// TIME: 1525735820 uTIME: 1525735821.001379 time() is behind
// TIME: 1525735821 uTIME: 1525735821.001718
// TIME: 1525735821 uTIME: 1525735821.002070
// TIME: 1525735821 uTIME: 1525735821.002425
// TIME: 1525735821 uTIME: 1525735821.002770
// TIME: 1525735821 uTIME: 1525735821.003109
// TIME: 1525735821 uTIME: 1525735821.003448
// TIME: 1525735821 uTIME: 1525735821.003787
// TIME: 1525735821 uTIME: 1525735821.004125
// TIME: 1525735821 uTIME: 1525735821.004480
Here’s a little tweak for those having trouble with cookies being set in the future or past (even after setting the date.timezone directive in php.ini or using the function):
Does anyone know if the year 2038 issue will be solved in PHP?
Lets imagine it’s year 2039 and the time() function will return negative numbers? This is not acceptable.
Using the DateTime interface is nice, but will these timestamp helper functions be removed or fixed?
If you want to create a «rounded» time stamp, for example, to the nearest 15 minutes use this as a reference:
= 60 * 15 // 60 seconds per minute * 15 minutes equals 900 seconds
//$round_numerator = 60 * 60 or to the nearest hour
//$round_numerator = 60 * 60 * 24 or to the nearest day
//If it was 12:40 this would return the timestamp for 12:45;
//3:04, 3:00; etc.
?>
I built this function to get the strtotime numbers for the beginning and ending of the month and return them as arrays in an object. Cheers.
The issue are highlighting is with the date() function, not with time(). the following code demonstrates this:
A better way to get a nice time-format (1 year ago, 2 months until) without all the trailing months, days, hours, minutes, seconds in the result is by using the DateTime format and using the date_diff function as they both does most of the heavy lifting for you
Function below as example
// Ex. (time now = November 23 2017)
getTimeInterval ( «2016-05-04 12:00:00» ); // Returns: 1 year ago
getTimeInterval ( «2017-12-24 12:00:00» ); // Returns: 1 month until
I did an article on floating point time you can download from my website. Roun movements is the radial ounion movement and there is a quantum ounion movement as well, this code will generate the data for http://www.chronolabs.org.au/bin/roun-time-article.pdf which is an article on floating point time, I have created the calendar system as well for this time. It is compatible with other time and other solar systems with different revolutions of the planets as well as different quantumy stuff.
Here’s one way to generate all intermediate dates (in mySQL format) between any 2 dates.
Get start and end dates from user input, you’d need to do the basic validations that :
— start and end dates are valid dates
— start date //start date 2001-02-23
$sm = 2 ;
$sd = 23 ;
$sy = 2001 ;
//end date 2001-03-14
$em = 3 ;
$ed = 14 ;
$ey = 2001 ;
A method return GMT time (gmttime):
elapsed time function with precision:
Here is a version for the difference code that displays «ago» code.
It does use some precision after the time difference is longer than a day. ( ie days are more than 60 * 60 * 24 hours long )
// Make the entered date into Unix timestamp from MySQL datetime field
// Calculate the difference in seconds betweeen
// the two timestamps
Convert UTC dates to local time in PHP
I’m storing the UTC dates into the DB using:
and then I want to convert the saved UTC date to the client’s local time.
11 Answers 11
PHP’s strtotime function will interpret timezone codes, like UTC. If you get the date from the database/client without the timezone code, but know it’s UTC, then you can append it.
Assuming you get the date with timestamp code (like «Fri Mar 23 2012 22:23:03 GMT-0700 (PDT)», which is what Javascript code «»+(new Date()) gives):
Or if you don’t, which is likely from MySQL, then:
Answer
Convert the UTC datetime to America/Denver
This works with dates after 2032, daylight savings and leap seconds and does not depend on the host machine locale or timezone.
It uses the timezonedb to do the calculation, this db changes over time as timezone rules change and has to be updated.
Notes
time() returns the unix timestamp, which is a number, it has no timezone.
date(‘Y-m-d H:i:s T’) returns the date in the current locale timezone.
gmdate(‘Y-m-d H:i:s T’) returns the date in UTC
date_default_timezone_set() changes the current locale timezone
to change a time in a timezone
here you can see all the available timezones
here are all the formatting options
Update PHP timezone DB (in linux)
Because of daylight savings, some dates repeat in some timezones, for example, in the United States, March 13, 2011 2:15am never occurred, while November 6, 2011 1:15am occurred twice. These datetimes can’t be accurately determined.