HOME HTML EDITOR C JAVA PHP

PHP Date and Time

The PHP date() function is used to format a date and/or a time. It can turn a timestamp into a more readable format for humans.

1. The date() Function

The syntax for the date function is: date(format, timestamp). The format parameter is required, while timestamp is optional (defaults to the current time).

<?php
  echo "Today is " . date("Y/m/d") . "<br>";
  echo "Today is " . date("Y.m.d") . "<br>";
  echo "Today is " . date("Y-m-d") . "<br>";
  echo "Today is " . date("l"); // Displays the day of the week
?>

Common Date Characters:

2. Get a Simple Time

To get the time, you use specific characters in the date function:

<?php
  echo "The time is " . date("h:i:sa");
?>

3. Get Your Time Zone

If the time returned is not correct, it is likely because your server is in another country. You can set the timezone specifically to your location.

<?php
  date_default_timezone_set("Asia/Kolkata");
  echo "The time in India is " . date("h:i:sa");
?>

4. Create a Date From a String

The strtotime() function is used to convert a human-readable string into a Unix timestamp.

<?php
  $d = strtotime("tomorrow");
  echo date("Y-m-d h:i:sa", $d) . "<br>";

  $d = strtotime("next Saturday");
  echo date("Y-m-d h:i:sa", $d) . "<br>";

  $d = strtotime("+3 Months");
  echo date("Y-m-d h:i:sa", $d);
?>
Tip: Always use date_default_timezone_set() at the top of your script if you are building an application that depends on local time (like a booking system or a log).