Php convert timestamp to unix timestamp

PHP Epoch Converter and Date/Time Routines

How to convert epoch / UNIX timestamps to normal readable date/time using PHP 7.

Getting current epoch time in PHP

Time returns an integer with the current epoch:

time() // current Unix timestamp microtime(true) // microtime returns timestamp with microseconds (param: true=float, false=string) 

Convert from epoch to human-readable date in PHP

1. Use the ‘date’ function.

$epoch = 1483228800; echo date('r', $epoch); // output as RFC 2822 date - returns local time echo gmdate('r', $epoch); // returns GMT/UTC time: Sun, 01 Jan 2017 00:00:00 +0000 

You can use the time zone code below (date_default_timezone_set) to switch the time zone of the input date.

2. Use the DateTime class.

$epoch = 1483228800; $dt = new DateTime("@$epoch"); // convert UNIX timestamp to PHP DateTime echo $dt->format('Y-m-d H:i:s'); // output = 2017-01-01 00:00:00 

In the examples above «r» and «Y-m-d H:i:s» are PHP date formats, other examples:

Читайте также:  Просмотр массива $GLOBALS
Format Output
r Wed, 15 Mar 2017 12:00:00 +0100 (RFC 2822 date)
c 2017-03-15T12:00:00+01:00 (ISO 8601 date)
M/d/Y Mar/15/2017
d-m-Y 15-03-2017
Y-m-d H:i:s 2017-03-15 12:00:00

Convert from human-readable date to epoch in PHP

strtotime parses most English language date texts to epoch/Unix Time.

echo strtotime("15 November 2017"); // . or . echo strtotime("2017/11/15"); // . or . echo strtotime("+10 days"); // 10 days from now 
if ((strtotime("this is no date")) === false)

2. Using the DateTime class:

The PHP DateTime class is nicer to use:

// object oriented $date = new DateTime('01/15/2017'); // format: MM/DD/YYYY echo $date->format('U'); // or procedural $date = date_create('01/15/2017'); echo date_format($date, 'U'); 

The date format ‘U’ converts the date to a UNIX timestamp.

This version is more of a hassle but works on any PHP version.

// PHP 5.1+ date_default_timezone_set('UTC'); // optional mktime ( $hour, $minute, $second, $month, $day, $year ); // example: generate epoch for Jan 1, 2000 (all PHP versions) echo mktime(0, 0, 0, 1, 1, 2000); 

All these PHP routines can’t handle dates before 13 December 1901.

Set your timezone

Use date_default_timezone_set to set/overrule your timezone.
The PHP time zone handling takes care of daylight saving times (list of available time zones).

date_default_timezone_set('Europe/Amsterdam'); date_default_timezone_set('America/New York'); date_default_timezone_set('EST'); date_default_timezone_set('UTC'); 

Convert date/time to another time zone

$TimeStr="2017-01-01 12:00:00"; $TimeZoneNameFrom="UTC"; $TimeZoneNameTo="Europe/Amsterdam"; echo date_create($TimeStr, new DateTimeZone($TimeZoneNameFrom)) ->setTimezone(new DateTimeZone($TimeZoneNameTo))->format("Y-m-d H:i:s"); 

Adding or subtracting years/months to a date

With strtotime you can easily add or subtract years/months/days/hours/minutes/seconds to a date.

$currentDate = time(); // get current date echo "It is now: ".date("Y-m-d H:i:s", $currentDate)."\n "; $date = strtotime(date("Y-m-d H:i:s", $currentDate) . " +1 year"); // add 1 year to current date echo "Date in epoch: ".$date."\n "; echo "Readable date: ".date("Y-m-d H:i:s",$date)."\n "; 
$date = strtotime(date("Y-m-d H:i:s", $currentDate) . " +1 month"); // add 1 month to a date $date = strtotime(date("Y-m-d H:i:s", $currentDate) . " +6 months"); // add 6 months $date = strtotime(date("Y-m-d H:i:s", $currentDate) . " +1 day"); // add 1 day $date = strtotime(date("Y-m-d H:i:s", $currentDate) . " -12 hours"); // subtract 12 hours $date = strtotime(date("Y-m-d H:i:s", $currentDate) . " -1 day -12 hours"); // subtract 1 day and 12 hours 

Источник

How to convert datetime in PHP to a Unix timestamp

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.

Overview

While working with the MySQL database in PHP, we may need to record the time instance at which an event occurs. This instance can be stored as a table record. We can the instance as a table record by using the datetime or timestamp MySQL data types. The problem associated with this procedure is that it cannot display the date in a very human-friendly and easily-readable format.

We get the following from the datetime and timestamp MySQL table columns:

But we may want to display the date in the format shown in the image below:

This shot teaches us how to display a date in this format, as a PHP script.

Before we learn to display the date in the aforementioned format, let’s look at the problems associated with MySQL table timestamp columns.

Problems

  • The datetime from the table is a string.
  • It comes from the database table column of type timestamp , which usually presents datetime in the format 2021-11-17 13:02:18 .
  • This format is not a Unix timestamp. We’ll need to convert the format to a Unix timestamp in order to get the date in the format shown in image above.

Converting datetime strings to a Unix timestamp

A combination of two PHP functions, the strtotime() and the date() functions, will produce an output like the one shown in the image above.

  • The strtotime() function converts any given date string into a Unix timestamp. It only accepts the date string as a parameter.
  • The date() function outputs the current time, or the time relative to the provided timestamp (if any), in the specified format. It takes the format we wish to display the date in and the optional timestamp as its two parameters.

Now, we will delve into some code examples.

The incorrect approach

The code below is an incorrect way of trying to get the output we’ve shown above, which may be our first approach while trying out solutions to that problem for the first time.

The output is not what we want, and that is because we didn’t convert the timestamp into a proper Unix timestamp before passing it to the date() function.

$mytimestamp = '2021-11-17 13:02:18';
// $dating = intval($mytimestamp);
// echo $dating;
$converted = date('m d, Y',$mytimestamp);
echo $converted;
?>

of a specific value fetched from the database in the provided code,##

The correct approach

In this second code, we use the strtotime() function to convert the datetime string from a database table into a Unix timestamp. Then, with the help of the date() function, we set the timestamp to various date formats of our choice.

What is the Unix timestamp?

This is the number of seconds since the Unix epoch time (01-01-1970) .

For more tips on the PHP date() function, we can see this post.

Note: The escape character is used in the code snippet below to escape the words that are just used as text, so that they are not given special interpretation by the function.

Code explanation

In the code below, a datetime string, saved in the variable $d , is converted to a Unix timestamp with the strtotime() function. It is then saved to the variable $ad on line 5.

Note: To use the current date and time instead of a specific value fetched from the database in the provided code, comment out $d = ‘2021-11-17 13:02:18’; with // and uncomment $d = date(‘Y-m-d H:i:s’); in the provided code, it will assign the current datetime to the variable $d .

Источник

PHP: Convert a date into a Unix timestamp.

This is a short PHP guide on how to convert a regular date string into a Unix timestamp. As you probably already know, “Unix Time” is the number of seconds that have passed since the 1st of January, 1970.

For the sake of this example, let’s say that we want to convert 2019-04-01 10:32:00 into an Epoch timestamp.

strtotime

To do this in PHP, we can use the strtotime function like so:

//Our date string. The format is Y-m-d H:i:s $date = '2019-04-01 10:32:00'; //Convert it into a Unix timestamp using strtotime. $timestamp = strtotime($date); //Print it out. echo $timestamp;

If you run the example above, you will see that 1554107520 is printed out onto the page. This is because 1554107520 passed between the Epoch time and 10:32AM on the 1st of April, 2019.

Note that the strtotime function will return a boolean FALSE value if the conversion fails.

Using the DateTime object.

If you prefer using OOP and the DateTime object, then you can do the following:

//Our date string. $date = '2019-04-01 10:32:00'; //Create a new DateTime object using the date string above. $dateTime = new DateTime($date); //Format it into a Unix timestamp. $timestamp = $dateTime->format('U'); //Print it out. echo $timestamp;

As you can see, it’s pretty similar to the strtotime approach. In the case above, we simply converted the date by passing the “U” format character into the DateTime “format” method.

Note that if you leave out the exact time, PHP will default to midnight:

//Create a DateTime object. $dateTime = new DateTime('2019-04-01'); //Format it into a Unix timestamp. echo $dateTime->format('U');

The above example will output “1554069600”, which is the Unix timestamp for midnight on the 1st of April, 2019.

By the way, in order to get the current timestamp, you can simply call PHP’s time function like so:

That’s it! Hopefully, you found this guide useful!

Источник

Convert a Date to a Timestamp in PHP

Convert a Date to a Timestamp in PHP

  1. Use strtotime() Function to Convert a Date to a Timestamp in PHP
  2. Use strptime() Function to Convert a Date to a Timestamp in PHP
  3. Use getTimestamp() Function to Convert a Date to a Timestamp in PHP
  4. Use format() Function to Convert a Date to a Timestamp in PHP

In this article, we will introduce methods to convert a date to a timestamp in PHP.

  • Using strtotime() function
  • Using strptime() function
  • Using getTimestamp() function
  • Using format() function

Use strtotime() Function to Convert a Date to a Timestamp in PHP

The built-in function strtotime() converts a date to a Unix timestamp . A Unix timestamp is the total number of seconds calculated from the Unix epoch(January 1st, 1970). The correct syntax to use this function is as follows

strtotime($dateString,$timeNow); 

This function has two parameters. $dateString is the date/time string that should comply with PHP valid format. It is a mandatory parameter. The other parameter $timeNow is optional, it is the timestamp that is used for calculating relative dates. The current time now is the default value if the second parameter is omitted.

php $timestamp = strtotime("23-04-2020"); echo "The timestamp is $timestamp."; ?> 

The date here is in the format «d-m-Y» . We have only passed a single parameter as it will convert the date to a Unix timestamp .

The timestamp is 1587600000. 

Use strptime() Function to Convert a Date to a Timestamp in PHP

This is another function to convert a date to a Unix timestamp . It does not convert the date directly to a timestamp . It returns an array that tells about the seconds, minutes, hours, and several other details. We can use these details to convert a date to a timestamp .

strptime($dateString, $format); 

It has two mandatory parameters. $dateString is the date string and $format is the format to parse $dateString .

php $array = strptime('23-04-2020', '%d-%m-%Y'); $timestamp = mktime(0, 0, 0, $array['tm_mon']+1, $array['tm_mday'], $array['tm_year']+1900); echo "The timestamp is $timestamp."; ?> 
The timestamp is 1587600000. 

After generating the array, mktime() function converts the date to a timestamp .

The syntax of mktime() function is

mktime(hour, minute, second, month, day, year, is_dst) 

is_dst specifies whether the date-time is a daylight saving time, but is removed from PHP 7.0.0.

We shall add 1 to $array[‘tm_mon’] and then use the sum as parameter of month in mktime , because $array[‘tm_mon’] starts from 0 , or in other words, $array[‘tm_mon’] of January is 0.

Use getTimestamp() Function to Convert a Date to a Timestamp in PHP

getTimestamp() method of DateTime object is a simple method to convert a date to a timestamp. It has another way of representation date_timestamp_get() that is the procedural style representation.

$datetimeObject->getTimestamp(); 

We will create a Datetime object to call this function. This is the object-oriented style of calling a function.

php $date = new DateTime('2020-04-23'); $timestamp = $date->getTimestamp(); echo "The timestamp is $timestamp."; ?> 

The object $date of Datetime class has called the method getTimestamp() to convert the date to a Unix timestamp .

The timestamp is 1587600000. 

Use format() Function to Convert a Date to a Timestamp in PHP

We can also use the format() method of DateTime to convert a date to a timestamp . This method has another representation date_format() that is the procedural style representation of the format() function.

To convert a date to a timestamp , the format that we will pass as a string is «U» .

php $dateObject = new DateTime('2020-04-23'); $timestamp = $dateObject->format("U"); echo "The timestamp is $timestamp."; ?> 

The object $dateObject of the Datetime class has called the function format() to convert the date to a Unix timestamp .

The timestamp is 1587600000. 

Related Article — PHP DateTime

Related Article — PHP Timestamp

Источник

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