Convert date to unix timestamp php

Convert date to unix timestamp php

  • Different ways to write a PHP code
  • How to write comments in PHP ?
  • Introduction to Codeignitor (PHP)
  • How to echo HTML in PHP ?
  • Error handling in PHP
  • How to show All Errors in PHP ?
  • How to Start and Stop a Timer in PHP ?
  • How to create default function parameter in PHP?
  • How to check if mod_rewrite is enabled in PHP ?
  • Web Scraping in PHP Using Simple HTML DOM Parser
  • How to pass form variables from one page to other page in PHP ?
  • How to display logged in user information in PHP ?
  • How to find out where a function is defined using PHP ?
  • How to Get $_POST from multiple check-boxes ?
  • How to Secure hash and salt for PHP passwords ?
  • Program to Insert new item in array on any position in PHP
  • PHP append one array to another
  • How to delete an Element From an Array in PHP ?
  • How to print all the values of an array in PHP ?
  • How to perform Array Delete by Value Not Key in PHP ?
  • Removing Array Element and Re-Indexing in PHP
  • How to count all array elements in PHP ?
  • How to insert an item at the beginning of an array in PHP ?
  • PHP Check if two arrays contain same elements
  • Merge two arrays keeping original keys in PHP
  • PHP program to find the maximum and the minimum in array
  • How to check a key exists in an array in PHP ?
  • PHP | Second most frequent element in an array
  • Sort array of objects by object fields in PHP
  • PHP | Sort array of strings in natural and standard orders
  • How to pass PHP Variables by reference ?
  • How to format Phone Numbers in PHP ?
  • How to use php serialize() and unserialize() Function
  • Implementing callback in PHP
  • PHP | Merging two or more arrays using array_merge()
  • PHP program to print an arithmetic progression series using inbuilt functions
  • How to prevent SQL Injection in PHP ?
  • How to extract the user name from the email ID using PHP ?
  • How to count rows in MySQL table in PHP ?
  • How to parse a CSV File in PHP ?
  • How to generate simple random password from a given string using PHP ?
  • How to upload images in MySQL using PHP PDO ?
  • How to check foreach Loop Key Value in PHP ?
  • How to properly Format a Number With Leading Zeros in PHP ?
  • How to get a File Extension in PHP ?
  • How to get the current Date and Time in PHP ?
  • PHP program to change date format
  • How to convert DateTime to String using PHP ?
  • How to get Time Difference in Minutes in PHP ?
  • Return all dates between two dates in an array in PHP
  • Sort an array of dates in PHP
  • How to get the time of the last modification of the current page in PHP?
  • How to convert a Date into Timestamp using PHP ?
  • How to add 24 hours to a unix timestamp in php?
  • Sort a multidimensional array by date element in PHP
  • Convert timestamp to readable date/time in PHP
  • PHP | Number of week days between two dates
  • PHP | Converting string to Date and DateTime
  • How to get last day of a month from date in PHP ?
  • PHP | Change strings in an array to uppercase
  • How to convert first character of all the words uppercase using PHP ?
  • How to get the last character of a string in PHP ?
  • How to convert uppercase string to lowercase using PHP ?
  • How to extract Numbers From a String in PHP ?
  • How to replace String in PHP ?
  • How to Encrypt and Decrypt a PHP String ?
  • How to display string values within a table using PHP ?
  • How to write Multi-Line Strings in PHP ?
  • How to check if a String Contains a Substring in PHP ?
  • How to append a string in PHP ?
  • How to remove white spaces only beginning/end of a string using PHP ?
  • How to Remove Special Character from String in PHP ?
  • How to create a string by joining the array elements using PHP ?
  • How to prepend a string in PHP ?
Читайте также:  Byte array to binary java

Источник

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.
Читайте также:  Css attribute selectors not

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!

Источник

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