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