0
0
PhpHow-ToBeginner · 3 min read

How to Get Current Time in PHP: Simple Guide

To get the current time in PHP, use the date() function with a format string like 'H:i:s' for hours, minutes, and seconds. Alternatively, use the DateTime class for more flexibility and timezone control.
📐

Syntax

The simplest way to get the current time is with the date() function. You provide a format string to specify how the time should look.

  • date(format): Returns a string with the current date/time formatted.
  • Format examples: 'H' for 24-hour, 'i' for minutes, 's' for seconds.

For more control, use the DateTime class:

  • new DateTime(): Creates an object with the current date and time.
  • format(format): Formats the DateTime object as a string.
php
<?php
// Using date() function
$current_time = date('H:i:s');
echo $current_time;

// Using DateTime class
$now = new DateTime();
echo $now->format('H:i:s');
?>
Output
14:35:20 14:35:20
💻

Example

This example shows how to print the current time in hours, minutes, and seconds using both date() and DateTime. It also sets the timezone to ensure the time is correct for your location.

php
<?php
// Set timezone to New York
date_default_timezone_set('America/New_York');

// Get current time using date()
echo "Current time using date(): " . date('H:i:s') . "\n";

// Get current time using DateTime
$now = new DateTime();
echo "Current time using DateTime: " . $now->format('H:i:s') . "\n";
?>
Output
Current time using date(): 14:35:20 Current time using DateTime: 14:35:20
⚠️

Common Pitfalls

One common mistake is forgetting to set the timezone, which can cause the time to be off by several hours. PHP uses the default timezone set in the configuration if you don't specify it.

Another mistake is using the wrong format characters in date(). For example, 'h' is 12-hour format, while 'H' is 24-hour format.

php
<?php
// Wrong: No timezone set, might show wrong time
echo date('H:i:s') . "\n";

// Right: Set timezone first
date_default_timezone_set('UTC');
echo date('H:i:s') . "\n";

// Wrong: Using 'h' for 24-hour format
 echo date('h:i:s') . " (12-hour format)\n";

// Right: Use 'H' for 24-hour format
 echo date('H:i:s') . " (24-hour format)\n";
?>
Output
14:35:20 14:35:20 02:35:20 (12-hour format) 14:35:20 (24-hour format)
📊

Quick Reference

Function/ClassPurposeExample Usage
date()Get current date/time as stringdate('H:i:s')
DateTimeObject for date/time with methodsnew DateTime(); $dt->format('H:i:s')
date_default_timezone_set()Set timezone for date/time functionsdate_default_timezone_set('America/New_York')

Key Takeaways

Use date('H:i:s') to get the current time as a string in 24-hour format.
Set the timezone with date_default_timezone_set() to get accurate local time.
Use the DateTime class for more flexibility and timezone handling.
Remember that 'H' is 24-hour and 'h' is 12-hour format in date strings.
Always check your server's timezone settings if the time looks incorrect.