Time with seconds php

PHP time

Summary: in this tutorial, you’ll learn how to work with the PHP time() function to get the current timestamp in the local timezone.

Introduction to Unix timestamps

Computers store a date and time as a UNIX timestamp or a timestamp in short.

A timestamp is an integer that refers to the number of seconds between 1970-01-01 00:00:00 UTC (Epoch) and the date and time to be stored.

Computers store dates and times as timestamps because it is easier to manipulate an integer. For example, to add one day to a timestamp, it simply adds the number of seconds to the timestamp.

PHP provides some helpful functions that manipulate timestamps effectively.

Getting the current time

To get the current time, you use the time() function:

function time(): intCode language: PHP (php)

The time() function returns the current UNIX timestamp since Epoch (January 1 1970 00:00:00 GMT). For example:

 echo time(); // 1626752728Code language: PHP (php)

The return value is a big integer that represents the number of seconds since Epoch. To make the time human-readable, you use the date() function. For example:

 $current_time = time(); echo date('Y-m-d g:ia', $current_time) . '
'
;
Code language: PHP (php)
2021-07-13 5:47amCode language: PHP (php)

The date() function has two parameters.

  • The first parameter specifies the date and time format. Here’s a complete list of valid date and time formats.
  • The second parameter is an integer that specifies the timestamp.

Since the time() function returns a timestamp, you can add seconds to it.

Adding to / subtracting from a timestamp

The following example shows how to add a week to the current time:

 $current_time = time(); // 7 days later $one_week_later = $current_time + 7 * 24 * 60 * 60; echo date('Y-m-d g:ia',$one_week_later);Code language: PHP (php)

In this example, we add 7 days * 24 hours * 60 minutes * 60 seconds to the current time.

Also, you can represent a time in the past by subtracting a number of seconds from the current time. For example:

 $current_time = time(); // 1 day ago $yesterday = $current_time - 24 * 60 * 60; echo date('Y-m-d g:ia',$yesterday);Code language: PHP (php)

timezone

By default, the time() function returns the current time in the timezone specified in the PHP configuration file (php.ini).

To get the current timezone, you can use the date_default_timezone_get() function:

 echo echo date_default_timezone_get(); Code language: PHP (php)

To set a specific timezone, you use the date_default_timezone_set() . It’s recommended that you use the UTC timezone.

The following shows how to use the date_default_timezone_set() function to set the current timezone to the UTC timezone:

 date_default_timezone_set('UTC');Code language: PHP (php)

Making a Unix timestamp

To make a Unix timestamp, you use the mktime() function:

mktime( int $hour, int|null $minute = null, int|null $second = null, int|null $month = null, int|null $day = null, int|null $year = null ): int|falseCode language: PHP (php)

The mktime() function returns a Unix timestamp based on its arguments. If you omit an argument, mktime() function will use the current value according to the local date and time instead.

The following example shows how to use the mktime() function to show that July 13, 2020, is on a Tuesday:

 echo 'July 13, 2021 is on a ' . date('l', mktime(0, 0, 0, 7, 13, 2021));Code language: PHP (php)

Summary

  • Use the time() function to return the current timestamp since Epoch in local timezone.
  • Use the date_default_timezone_set() function to set a specific timezone.
  • Use the date() function to format the timestamp.
  • Use mktime() function to create a timestasmp based on the year, month, day, hour, minute, and second.

Источник

time

Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

Note:

Unix timestamps do not contain any information with regards to any local timezone. It is recommended to use the DateTimeImmutable class for handling date and time information in order to avoid the pitfalls that come with just Unix timestamps.

Parameters

This function has no parameters.

Return Values

Returns the current timestamp.

Examples

Example #1 time() example

The above example will output something similar to:

Notes

Timestamp of the start of the request is available in $_SERVER[‘REQUEST_TIME’] .

See Also

  • DateTimeImmutable
  • date() — Format a Unix timestamp
  • microtime() — Return current Unix timestamp with microseconds

User Contributed Notes 1 note

time() gives the timestamp of Greenwich Mean Time (GMT) which is defined as the official time for the whole earth. You get the local time by adding the time zone offset to this timestamp.

  • Date/Time Functions
    • checkdate
    • date_​add
    • date_​create_​from_​format
    • date_​create_​immutable_​from_​format
    • date_​create_​immutable
    • date_​create
    • date_​date_​set
    • date_​default_​timezone_​get
    • date_​default_​timezone_​set
    • date_​diff
    • date_​format
    • date_​get_​last_​errors
    • date_​interval_​create_​from_​date_​string
    • date_​interval_​format
    • date_​isodate_​set
    • date_​modify
    • date_​offset_​get
    • date_​parse_​from_​format
    • date_​parse
    • date_​sub
    • date_​sun_​info
    • date_​sunrise
    • date_​sunset
    • date_​time_​set
    • date_​timestamp_​get
    • date_​timestamp_​set
    • date_​timezone_​get
    • date_​timezone_​set
    • date
    • getdate
    • gettimeofday
    • gmdate
    • gmmktime
    • gmstrftime
    • idate
    • localtime
    • microtime
    • mktime
    • strftime
    • strptime
    • strtotime
    • time
    • timezone_​abbreviations_​list
    • timezone_​identifiers_​list
    • timezone_​location_​get
    • timezone_​name_​from_​abbr
    • timezone_​name_​get
    • timezone_​offset_​get
    • timezone_​open
    • timezone_​transitions_​get
    • timezone_​version_​get

    Источник

    Получить метку времени в секундах в PHP

    В этой статье показано, как получить текущую временную метку Unix в секундах в PHP.

    1. Использование time() функция

    Вы можете использовать time() для получения текущей временной метки Unix в секундах. Это эквивалентно количеству секунд, прошедших с эпохи Unix (1 января 1970 г. по Гринвичу).

    Чтобы получить отметку времени начала запроса вместо текущего времени, рассмотрите возможность использования $_SERVER[‘REQUEST_TIME’] переменная.

    2. Использование gettimeofday() функция

    Другой альтернативой получению текущего времени является использование gettimeofday() функция, которая возвращает массив с ‘sec’ , ‘usec’ , ‘minuteswest’ , а также ‘dsttime’ как ключи. Чтобы получить количество секунд, прошедших с эпохи Unix, вы можете использовать значение, соответствующее ‘sec’ ключ из возвращаемого массива.

    The gettimeofday() функция необязательно принимает логическое значение true , что заставляет функцию возвращать значение с плавающей запятой, а не строку. Чтобы получить целочисленную отметку времени в секундах, вы всегда можете округлить значение в меньшую сторону, используя floor() функция.

    3. Использование DateTime::format() функция

    Наконец, вы можете использовать объектно-ориентированную функцию DateTime::format() для форматирования даты в соответствии с заданным форматом. Чтобы получить количество секунд, прошедших с эпохи Unix, вы можете отформатировать дату, используя U параметр.

    В качестве альтернативы вы можете использовать процедурную функцию date_format() чтобы получить количество секунд с эпохи Unix с U параметр формата.

    Это все, что нужно для получения текущей метки времени Unix в секундах в PHP.

    Средний рейтинг 5 /5. Подсчет голосов: 1

    Голосов пока нет! Будьте первым, кто оценит этот пост.

    Сожалеем, что этот пост не оказался для вас полезным!

    Расскажите, как мы можем улучшить этот пост?

    Спасибо за чтение.

    Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

    Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

    Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно

    Источник

    Читайте также:  Содержать специальную html разметку позволяющую однозначно идентифицировать информацию
Оцените статью