Php timestamp from date format

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.

Читайте также:  Python days from timedelta

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 .

Источник

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

Источник

Converting a PHP timestamp to a date(time)

In this PHP tutorial, we’re going to convert a timestamp in PHP to a date (optionally with time) using custom formatting. We’ll start by getting the current time stamp and display it using the simple date function. Next, we’ll use the current timestamp to create a Date Time object, format the date and display it. We’ll then view some of the date and time formatting options, followed by the Date Time Zone class. And finally, we’ll create a function to convert a timestamp to DateTime with time zone and date format parameters.

In this article

Getting a Timestamp

Let’s start with a basic PHP function to get the timestamp, we’ll use time() to get the current timestamp and date to format the output.

The time stamp saved in $now is similar to 1610246191, so we format it using date(‘Y-m-d’, $now) for a user friendly output. The timestamp returned is in seconds, see the microtime function to get a timestamp including micro seconds.

Timestamp To Date Time Object

While we can use the date function to format our date or timestamp, it isn’t the object oriented way of doing it. Let’s create a DateTime object and set the timestamp.

We can then output the date and time using the format method with the ‘c’ datetime parameter.

Formatting a Date

The format method can format a date in many different ways, common formats are: Y-m-d and d/m/Y .

The PHP manual has many more date formats available.

Formatting a Time

The DateTime class can also format the same timestamp in time only format.

We use the H:i:s(Hour, Minute, Second) format in the code above.

Date with TimeZone

The DateTime object can be set to use a specific time zone. We create a new DateTimeZone with a particular time zone and call the setTimeZone method on our DateTime object.

The DateTimeZone class has many timezone options. The PHP code example above displays the same timestamp using different time zones.

Converting a Timestamp to Date Time

Our final function is a combination of DateTime and DateTimeZone with 3 parameters: a timestamp, time zone and date/time format with default formatting.

Our custom PHP function timeStampToDateTime takes a timestamp as first parameter, which could be the current timestamp or any other time stamp (maybe a timestamp from a db). It uses the timezone and format to return a human readable date time string.

Key Takeaways

  • We can use the time() function to get the current timestamp and the date function to format a timestamp.
  • The DateTime class is the object oriented way of working with dates and times.
  • The DateTimeZone class provides time zone functionality which can be used with the DateTime class to work with dates and times.
  • The format , setTimeZone and setTimeStamp methods are the primary methods we can use to convert a timestamp to date/time.
  • Related PHP functions: microtime

This is the footer. If you’re reading this, it means you’ve reached the bottom of the page.
It would also imply that you’re interested in PHP, in which case, you’re in the right place.
We’d love to know what you think, so please do check back in a few days and hopefully the feedback form will be ready.

Источник

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