Php get timestamp with timezone

The complete guide on working with dates and time in PHP

As a developer, nearly every application you will work on requires the use of time in some way. You will need to keep a record of the time in which various activities occur, such as the time in which a record is created, updated, deleted, when a user logs in, etc.

At some point, you’re going to have to collect, store, retrieve and display dates and times in different formats. You are also likely to do calculations involving time such as adding days to a day, subtracting a number of days from a date, comparing two days, etc.

In this article, we will cover in detail working with dates and times in PHP.

How computers count time

Computers count time from an instant called Unix epoch, which occurred on January 1, 1970, at 00:00:00 UTC(Coordinated Universal Time). UTC is also known as GMT(Greenwich Meridian Time), which is the time at a longitude of 0°.

Unix time elapses at the same rate as UTC. You can calculate the UTC date and time of any given instant since January 1, 1970, by counting the number of seconds since the Unix epoch, with the exception of leap seconds. Leap seconds are occasionally added to UTC to account for the slowing of the Earth’s rotation but are not added to Unix time.

Unix Timestamp

Unix timestamp is the number of seconds that have elapsed since January 1, 1970, at 00:00:00 UTC.

Standard Dates Reporting

Computers count time using Unix timestamp, calculating the number of seconds that have passed since Jan 1, 1970. However, this would be difficult and incredibly inefficient for humans. Thus, we work in terms of years, months, days, hours, minutes, and seconds.

But this also comes with complexities because different regions and cultures have different ways of writing the date. For instance, dates in the United States are written starting with the month, then day, then the year. December 31, 2021, will be written as 12-31-2021. On the other hand, the same date will be written as 31-12-2021 in Europe and other regions.

To standardize the date and help fix the communication mistakes, the International Organization for Standardization (ISO) introduced ISO8601. This standard specifies that all dates should be written in order of most-to-least-significant data. This means the format is the year, month, day, hour, minute, and second:

In the example above, YYYY represents a four-digit year, and MM and DD are the two-digit month and day, starting with a zero if less than 10. After that, HH, MM, and SS represent the two-digit hours, minutes, and seconds, starting with a zero if less than 10.

Читайте также:  Python requests post header

The above format eliminates the ambiguity in dates representation, where dates written as DD-MM-YYYY or MM-DD-YYYY can be misinterpreted if the day is a valid month number.

Most databases use YYYY-MM-DD HH:MM:SS format to store date and time and YYYY-MM-DD to store date.

Setting and getting timezone on your server

Different regions of the world have different timezones. You can know which timezone your web server is set to with the following PHP function.

To change to the timezone that will be used in your date and time functions in PHP, you do it with the function date_default_timezone_set($timezoneId), where $timezoneId is a string value.

The above code sets the timezone to that of Nairobi, Kenya. You can get a list of all timezones on this link

Unless all your website/app users are from the same region, it is always advisable to set your server time zone to UTC.

Below is how you set timezone to UTC in PHP:

For the date and time functions to pick and reflect the timezone specific time, you should always the function for setting the timezone at the top.

Timestamp function: time()

The function returns the current unix timestamp, ie. total number of seconds that have passed since January 1, 1970 at 00:00:00 UTC.

PHP date() function

The function returns a string formatted according to the given format string using the given integer timestamp.

It takes the format below:

Where $format is a string value and $timestamp an optional integer unix timestamp value.If $timestamp is not given, the function defaults to the value of time()

Date function formatting options

To convert/format a date in different formats using the date() function, you need to first convert that date into a Unix timestamp using the strtotime() function.

Conversion of date/time to Unix timestamp

The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT).

Example 2: Displaying current time in DateTime format

Converting a date into different formats

You can convert the date into as many formats as possible by just manipulating various letters in the table above to form within the date() function, enclosed in single or double-quotes.

Adding and subtracting days or time to a DateTime

The easiest way to add or subtract time to/from date in PHP is by concatenating a string specifying the duration of time you want to add or subtract, to date, inside the strtotime() function, preceded with the plus (+) or minus (-) symbol.

Adding time to the current time

Adding time to a DateTime

Adding days, weeks, months and years to a date

How to subtract 2 dates in PHP

When you have two dates that you want to find their difference, PHP can help you find it.

You just convert the two dates to unix timestamps, subtract the two timestamps and find the difference between the two dates in seconds.

Читайте также:  External css code in html

You then convert the time in seconds to the duration in which you want to measure the time in eg. hours, days, years, etc.

If you use DateTime format(date and time in the date), use the floor() function to round down and avoid decimals in time difference like below.

Comparison between 2 dates

It is quite easy to compare two dates and know which is older than the other.

If the two dates are exactly in the same format, you just compare them directly as below:

If the two dates have different formats, you will first need to convert the two to the Unix timestamp, then compare them as below.

Conclusion

Nearly in all applications, you will ever work on as a developer, in whatever language you decide to use, you will have to work with dates and time in one way or another.

In this article, we have covered working with dates in PHP. We have covered how computers count time, what Unix timestamp is, how to collect the current time, working with timezones, converting dates and time into multiple different formats, adding or subtracting time to or from a date, and dates comparison among other things.

Источник

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 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.

    Источник

Оцените статью