Home » PHP » PHP Date and Time
This tutorial enables you to learn the PHP Date and Time function. So, let's begin.
Syntax
date(format,timestamp)
Parameter | Description |
---|---|
format | Required. It is used for specifying the format of the timestamp. |
timestamp | Optional. It is used for specifying a timestamp. Default is the current date and time. |
You can specify how to format the date (or time) using the required format parameter of the date() function.
Some characters which are commonly used for dates are mentioned here:
You can also insert other characters, such as "/", ".", or "-" between the characters to add additional formatting.
The below-mentioned example formats today's date in three different ways:
<?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");
?>
Output:
Run this and check on you browser.
My output
Today is 2022/04/30
Today is 2022.04.30
Today is 2022-04-30
Today is Tuesday
Some characters that are commonly used for time are mentioned here:
The below-mentioned example outputs the current time in the specified format:
<?php
echo "The time is " . date("h:i:sa");
?>
If the time you get back from the code is incorrect, the most probable reason behind this is that your server is located in another country, or it is set up for a different timezone.
So, if you want the time to be displayed according to a specific location, you can set the timezone you want to use.
The below-mentioned example sets the timezone to "America/New_York", then outputs the current time in the specified format:
<?php
date_default_timezone_set("America/New_York");
echo "The time is " . date("h:i:sa");
?>
You can use the optional timestamp parameter in the date() function to specify a timestamp. In case it is omitted, the current date and time will be used (as in the examples mentioned above).
The Unix timestamp for a date is returned by the PHP mktime() function. The no. of seconds between the Unix Epoch (January 1, 1970, 00:00:00 GMT) and the specified time are contained in the Unix timestamp.
Syntax
mktime(hour, minute, second, month, day, year)
The below-mentioned example creates a date and time with the date() function from multiple parameters in the mktime() function:
<?php
$d=mktime(11, 14, 54, 8, 12, 2022);
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>
You can use the PHP strtotime() function to convert a human-readable date string into a Unix timestamp (the no. of seconds since January 1, 1970, 00:00:00 GMT).
Syntax:
strtotime(time, now)
<?php
$d=strtotime("10:30pm April 15 2014");
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>