php time from date

Php time from date

(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

Источник

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

Источник

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 time from date

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

date — Форматирует вывод системной даты/времени

Описание

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

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

Ошибки

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

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

Примеры

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

// установка часового пояса по умолчанию.
date_default_timezone_set ( ‘UTC’ );

// выведет примерно следующее: Monday
echo date ( «l» );

// выведет примерно следующее: Monday 8th of August 2005 03:12:46 PM
echo date ( ‘l jS \of F Y h:i:s A’ );

/* пример использования константы в качестве форматирующего параметра */
// выведет примерно следующее: Mon, 15 Aug 2005 15:12:46 UTC
echo date ( DATE_RFC822 );

Чтобы запретить распознавание символа как форматирующего, следует экранировать его с помощью обратного слеша. Если экранированный символ также является форматирующей последовательностью, то следует экранировать его повторно.

Пример #2 Экранирование символов в функции date()

Пример #3 Пример совместного использования функций date() и mktime()

Данный способ более надёжен, чем простое вычитание и прибавление секунд к метке времени, поскольку позволяет при необходимости гибко осуществить переход на летнее/зимнее время.

Пример #4 Форматирование с использованием date()

// Предположим, что текущей датой является 10 марта 2001, 5:16:18 вечера,
// и мы находимся в часовом поясе Mountain Standard Time (MST)

$today = date ( «F j, Y, g:i a» ); // March 10, 2001, 5:16 pm
$today = date ( «m.d.y» ); // 03.10.01
$today = date ( «j, n, Y» ); // 10, 3, 2001
$today = date ( «Ymd» ); // 20010310
$today = date ( ‘h-i-s, j-m-y, it is w Day’ ); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date ( ‘\i\t \i\s \t\h\e jS \d\a\y.’ ); // it is the 10th day.
$today = date ( «D M j G:i:s T Y» ); // Sat Mar 10 17:16:18 MST 2001
$today = date ( ‘H:m:s \m \i\s\ \m\o\n\t\h’ ); // 17:03:18 m is month
$today = date ( «H:i:s» ); // 17:16:18
$today = date ( «Y-m-d H:i:s» ); // 2001-03-10 17:16:18 (формат MySQL DATETIME)
?>

Примечания

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

User Contributed Notes 20 notes

Things to be aware of when using week numbers with years.

Conclusion:
if using ‘W’ for the week number use ‘o’ for the year.

In order to define leap year you must considre not only that year can be divide by 4!

The correct alghoritm is:

if (year is not divisible by 4) then (it is a common year)
else if (year is not divisible by 100) then (it is a leap year)
else if (year is not divisible by 400) then (it is a common year)
else (it is a leap year)

So the code should look like this:

For Microseconds, we can get by following:

echo date(‘Ymd His’.substr((string)microtime(), 1, 8).’ e’);

FYI: there’s a list of constants with predefined formats on the DateTime object, for example instead of outputting ISO 8601 dates with:

echo date ( ‘Y-m-d\TH:i:sO’ );
?>

You can use

echo date ( DateTime :: ISO8601 );
?>

instead, which is much easier to read.

this how you make an HTML5 tag correctly

It’s common for us to overthink the complexity of date/time calculations and underthink the power and flexibility of PHP’s built-in functions. Consider http://php.net/manual/en/function.date.php#108613

date() will format a time-zone agnostic timestamp according to the default timezone set with date_default_timezone_set(. ). Local time. If you want to output as UTC time use:

$tz = date_default_timezone_get ();
date_default_timezone_set ( ‘UTC’ );

For HTML5 datetime-local HTML input controls (http://www.w3.org/TR/html-markup/input.datetime-local.html) use format example: 1996-12-19T16:39:57

To generate this, escape the ‘T’, as shown below:

If timestamp is a string, date converts it to an integer in a possibly unexpected way:

The example below formats today’s date in three different ways:

The following function will return the date (on the Gregorian calendar) for Orthodox Easter (Pascha). Note that incorrect results will be returned for years less than 1601 or greater than 2399. This is because the Julian calendar (from which the Easter date is calculated) deviates from the Gregorian by one day for each century-year that is NOT a leap-year, i.e. the century is divisible by 4 but not by 10. (In the old Julian reckoning, EVERY 4th year was a leap-year.)

This algorithm was first proposed by the mathematician/physicist Gauss. Its complexity derives from the fact that the calculation is based on a combination of solar and lunar calendars.

At least in PHP 5.5.38 date(‘j.n.Y’, 2222222222) gives a result of 2.6.2040.

So date is not longer limited to the minimum and maximum values for a 32-bit signed integer as timestamp.

Prior to PHP 5.6.23, Relative Formats for the start of the week aligned with PHP’s (0=Sunday,6=Saturday). Since 5.6.23, Relative Formats for the start of the week align with ISO-8601 (1=Monday,7=Sunday). (http://php.net/manual/en/datetime.formats.relative.php)

This can produce different, and seemingly incorrect, results depending on your PHP version and your choice of ‘w’ or ‘N’ for the Numeric representation of the day of the week:

Prior to PHP 5.6.23, this results in:

Today is Sun 2 Oct 2016, day 0 of this week. Day 1 of next week is 10 Oct 2016
Today is Sun 2 Oct 2016, day 7 of this week. Day 1 of next week is 10 Oct 2016

Since PHP 5.6.23, this results in:

Today is Sun 2 Oct 2016, day 0 of this week. Day 1 of next week is 03 Oct 2016
Today is Sun 2 Oct 2016, day 7 of this week. Day 1 of next week is 03 Oct 2016

I’ve tested it pretty strenuously but date arithmetic is complicated and there’s always the possibility I missed something, so please feel free to check my math.

The function could certainly be made much more powerful, to allow you to set different days to be ignored (e.g. «skip all Fridays and Saturdays but include Sundays») or to set up dates that should always be skipped (e.g. «skip July 4th in any year, skip the first Monday in September in any year»). But that’s a project for another time.

$start = strtotime ( «1 January 2010» );
$end = strtotime ( «13 December 2010» );

// Add as many holidays as desired.
$holidays = array();
$holidays [] = «4 July 2010» ; // Falls on a Sunday; doesn’t affect count
$holidays [] = «6 September 2010» ; // Falls on a Monday; reduces count by one

?>

Or, if you just want to know how many work days there are in any given year, here’s a quick function for that one:

Источник

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

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