Php date time to utc

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

Читайте также:  Php add http to url

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.

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.

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.

Источник

Get UTC Time in PHP

Get UTC Time in PHP

  1. Use gmdate() to Get UTC Time
  2. Use strtotime() to Get UTC Time
  3. Use date() to Get UTC Time
  4. Use date_default_timezone_set() to Get UTC Time
  5. Use DateTime Object to Get UTC Time

This article teaches you how to get UTC in PHP using five methods. These methods will use date_default_timezone_set() , gmdate() , strtotime() , date() , and the DateTime object.

Use gmdate() to Get UTC Time

The gmdate() function will format a date and time in UTC. Once you supply gmdate() with your date time format, e.g. Y-m-d H:i:s , it’ll show it in UTC.

We’ve set the current time zone in the following code to Detroit, Michigan. This will show the time in Detroit and what it’s like in UTC.

php  // Use the time in Detroit, Michigan, as the default  // time.  date_default_timezone_set("America/Detroit");   // We get the current time in Detroit, Michigan.  $time_in_Detroit = date('Y-m-d H:i:s', time());   // We get the UTC time using the gmdate() function  $utc_time = gmdate("Y-m-d H:i:s");   // For comparison, we show the time in Detroit and  // what it'll be in UTC.  echo "The current time in Detroit is: " . $time_in_Detroit . PHP_EOL;  echo "The UTC is: " . $utc_time; ?> 

Output (you’ll have different results):

The current time in Detroit is: 2022-07-27 17:32:36 The UTC is: 2022-07-27 21:32:36 

Use strtotime() to Get UTC Time

The method strtotime() will parse a textual date time into a Unix timestamp. After that, you can do what you want with the timestamp.

In the following code, we get a timestamp from strtotime() using gmdate() . Then we pass the timestamp as the second parameter of the date() function.

Doing this allows you to write your date format and get the result in UTC. For comparison, we’ve set the time zone of the script to Guatemala.

php  // Use the time in Guatemala as the default  // time.  date_default_timezone_set("America/Guatemala");   // We get the current time in Guatemala  $time_in_Guatemala = date('Y-m-d H:i:s', time());   // We get the UTC UNIX timestamp  $utc_timestamp = strtotime(gmdate("M d Y H:i:s"));   // We convert the UNIX timestamp to UTC  $utc_time = date('Y-m-d H:i:s', $utc_timestamp);   // For comparison, we show the time in Guatemala  // and what it'll be in UTC.  echo "The time in Guatemala is: " . $time_in_Guatemala . PHP_EOL;  echo "The UTC is: " . $utc_time; ?> 

Output (you’ll have different results):

The time in Guatemala is: 2022-07-27 15:48:01 The UTC is: 2022-07-27 21:48:01 

Use date() to Get UTC Time

We’ll use the date() function to format a date, but with some math, date() will return the UTC. The math involves subtracting the time zone offset from the epoch time, and then you pass the result as the second parameter of the date() function.

For comparison, we’ve changed the time zone to Adelaide, Australia. When you run the code below, you’ll see the UTC and what it’s like in Adelaide.

 php  // Use the time in Adelaide, Australia, as the default  // time.  date_default_timezone_set("Australia/Adelaide");   // We get the current time in Adelaide  $time_in_Adelaide = date('Y-m-d H:i:s', time());   // We get the UTC time using the date() function.  $utc_time = date("Y-m-d H:i:s", time() - date("Z"));   // For comparison, we show the time in Adelaide  // and what it'll be in UTC.  echo "The time in Adelaide is: " . $time_in_Adelaide . PHP_EOL;  echo "The UTC is: " . $utc_time; ?> 

Output (you’ll have different results):

The time in Adelaide is: 2022-07-28 07:56:31 The UTC is: 2022-07-27 22:26:31 

Use date_default_timezone_set() to Get UTC Time

The date_default_timezone_set() function is used to change the time zone. We can also use it to return the UTC by changing its parameter to UTC .

As a result, it’ll always be in UTC, irrespective of the time in the PHP script.

php  // Set the default time zone to UTC and all  // date and time of the current PHP script will  // be in UTC.  date_default_timezone_set("UTC");   // As usual, get the date, but this time, it'll  // return the time in UTC. That's because this script  // has its time zone set to UTC.  $utc_time = date('Y-m-d H:i:s', time());  echo "The UTC is: " . $utc_time; ?> 

Output (you’ll have different results):

The UTC is: 2022-07-27 22:36:02 

Use DateTime Object to Get UTC Time

A combination of the DateTime object and the DateTimeZone object can return the UTC. To return the UTC, set the first and second parameters of DateTime to now and new \DateTimeZone(«UTC») , and then you can show the result in RFC 850 format.

php  // Get the UTC using the DateTime object.  // Its first parameter should be the  // string "now". And its second parameter should  // be a new DateTimeZone object and its parameter  // should be the string "UTC".  $utc_time = new \DateTime("now", new \DateTimeZone("UTC"));   // Format the date to show it's a UTC date  // A sample output is: Wednesday, 27-Jul-22 15:02:41 UTC  echo $utc_time->format(\DateTime::RFC850); ?> 

Output (you’ll have different results):

Wednesday, 27-Jul-22 23:00:42 UTC 

Habdul Hazeez is a technical writer with amazing research skills. He can connect the dots, and make sense of data that are scattered across different media.

Related Article — PHP Time

Источник

How to Convert Local DateTime to UTC in PHP

Timezone conversion to a specific timezone helps to synchronize different DateTime. It is very useful to balance the server time and the user’s local time. PHP DateTime class provides an easy way to convert a date time stamp to UTC. You can convert any timezone to UTC DateTime using PHP.

In the example code snippet, we will show you how to convert local date&time to UTC DateTime (YYYY-MM-DD HH:MM:SS format) in PHP.

Convert Current DateTime to UTC DateTime using PHP:

$dateTime = date("Y-m-d H:i:s"); 
$newDateTime = new DateTime($dateTime);
$newDateTime->setTimezone(new DateTimeZone("UTC"));
$dateTimeUTC = $newDateTime->format("Y-m-d H:i:s");

Convert Local DateTime to UTC DateTime using PHP:

$dateTime = '2021-04-28 18:37:54'; 
$tz_from = 'America/New_York';
$newDateTime = new DateTime($dateTime, new DateTimeZone($tz_from));
$newDateTime->setTimezone(new DateTimeZone("UTC"));
$dateTimeUTC = $newDateTime->format("Y-m-d H:i:s");

Источник

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