Time and date in PHP

Iterables in PHP
Introduction to MySQL/PHP

PHP has a number of methods for working with PHP time functions, such as acquiring the current time and date, manipulating dates, and formatting dates for display.

  1. Getting the current time and date:
  • The time() function returns the current timestamp, which is the number of seconds since January 1st, 1970.
  • The date() function can be used to format the current date and time according to a specified format.
  • The getdate() function returns an associative array containing information about the current date and time.
  • The microtime() function returns the current timestamp with microseconds.
  1. Manipulating dates:
  • The strtotime() function can be used to convert a date string to a timestamp.
  • The mktime() function can be used to create a timestamp for a specific date and time.
  • The date_create() and date_create_from_format() functions can be used to create a new date object.
  • The date_modify() function can be used to modify a date object.
  1. Formatting dates for display:
  • The date() function can be used to format a timestamp or date object according to a specified format.
  • The date_format() function can be used to format a date object according to a specified format.
  • The strftime() function can be used to format a timestamp or date object according to a specified format and locale.
  1. Timezone functions:
  • The date_default_timezone_set() function can be used to set the default timezone.
  • The date_default_timezone_get() function can be used to get the default timezone.
  • The date_timezone_set() function can be used to set the timezone for a date object.
  • The date_timezone_get() function can be used to get the timezone for a date object.
  1. Calendar functions:
  • The cal_days_in_month() function can be used to get the number of days in a month for a given year and calendar.
  • The cal_from_jd() function can be used to convert a Julian day count to a calendar date.
  • The cal_info() function can be used to get information about a calendar.
  • The easter_date() and easter_days() functions can be used to calculate the date of Easter.

It’s worth noting that while working with date and time functions, it’s critical to keep the server’s and client’s timezone and daylight saving time (DST) settings in mind. When these parameters are handled incorrectly, mistakes and unexpected effects might occur.

In summary, PHP has methods for acquiring the current time and date, manipulating dates, formatting dates for display, and managing timezones and calendar functions. You may increase the accuracy and functionality of your PHP programs by knowing these functions.

  1. Getting the current time and date:
  • The time() function returns the current timestamp, which is the number of seconds since January 1st, 1970. The timestamp is a widely used format for storing and comparing dates and times in computer systems. It’s useful for tracking the duration of events, comparing dates and times, and generating unique IDs.
$timestamp = time();
echo "Current timestamp: " . $timestamp . "<br>";

The date() method may be used to format the current date and time to a custom format. The format string and the timestamp are the only parameters accepted by the date function. If no timestamp is given, the current timestamp is used.

$current_date = date('Y-m-d H:i:s');
echo "Current date: " . $current_date . "<br>";

The getdate() method produces an associative array containing current date and time information. It only takes one parameter, the timestamp, which is set to the current timestamp if not specified. The returned array comprises data such as the weekday, month, and year.

$date_array = getdate();
print_r($date_array);

The current timestamp in microseconds is returned by the microtime() method. It is handy for determining the length of scripts and functions. The function returns a float value including the timestamp and the number of microseconds.

$microtime = microtime();
echo "Current microtime: " . $microtime . "<br>";
  1. Manipulating dates:
  • To convert a date string to a timestamp, use the strtotime() method. As an argument, the function accepts a string in a number of forms, such as ‘yesterday,’ ‘+1 week,’ ‘next Monday,’ and so on. This method can be used to transform user input into a timestamp for additional processing or comparison.
$date_string = 'next Monday';
$timestamp = strtotime($date_string);
echo "Timestamp for " . $date_string . ": " . $timestamp . "<br>";

To generate a timestamp for a certain day and time, use the mktime() method. It accepts six parameters, which indicate the year, month, day, hour, minute, and second. It returns the timestamp for the date and time supplied.

$year = 2022;
$month = 11;
$day = 23;
$hour = 12;
$minute = 30;
$second = 0;
$timestamp = mktime($hour, $minute, $second, $month, $day, $year);
echo "Timestamp for " . date('Y-m-d H:i:s', $timestamp) . ": " . $timestamp . "<br>";

The date_create() and date_create_from_format() functions can be used to create a new date object.

Date($time, $format)

Parameters

Format  Set the format of the timestamp in the returned value. This function accept all formats accepted by DateTimeInterface::format().
TimestampSet the timestamp in the returned value. By default, it returns the current date and time. In other words, it defaults to the value of the time() function.  

To define the format, you must be familiar with the characters that indicate the matching format.

dRepresents the day of the month (01 to 31)
mRepresents a month (01 to 12)
yRepresents a year (in four digits)
l(lowercase ‘L’) – Represents the day of the week

In PHP 8.0 the timestamp is now nullable.

Return value

SuccessIt returns a string formatted as defined by the format parameter.  
Errors/ExceptionsIf the time zone is not valid date function will return E_WARNING.  

To learn about valid time zones you can go to this link.

Example

Return the current date in the specified format.

<?php
echo " Date is " . date("Y/m/d") . " ";
echo " Date is " . date("Y.m.d") . " ";
echo " Date is " . date("Y-m-d") . " ";
echo " Date is " . date("l");
?>

How to use the date function to get the current time in PHP

Pass the time characters into the date function to receive the current time in the specified format. The following are the most essential and useful time characters in PHP.

H24-hour format of an hour (00 to 23)
h12-hour format of an hour with leading zeros (01 to 12)
iMinutes with leading zeros (00 to 59)
sSeconds with leading zeros (00 to 59)
aLowercase Ante meridiem and Post meridiem (am or pm)
Get the current time in a specific format
<?php
echo "Curent time is " . date("H:i:s");
?>

Does the date function return client time or server time?

The function above will output the current time. The crucial thing to remember here is that the date function returns the server machine’s current date and time. Most folks are perplexed as to why this function does not return client time.

How to set the time zone of the date function in PHP?

If you are not obtaining the right time using the previous example, it is possible that your server was placed in another country and the time zones of your present location and server location are different. In this scenario, you may set the time zone of the date function using the date default timezone set(“Asia”); function.

<?php
date_default_timezone_set("Asia");
echo "The server time in my zone is " . date("h:i:sa");
?>

What is the UNIX time stamp?

The Unix timestamp is the number of seconds between 01 January-1970 and the current time specified.

How to create a date in php

You can create your own timestamp or date in PHP using the time function. In this section, you will learn about mktime function in PHP 8.

mktime(hour, minute, second, month, day, year)

The parameters of the function are clear by their names. Here is an example:

<?php
$date=mktime(7, 11, 34, 6, 09, 2021);
echo "My created date is " . date("Y-m-d h:i:s", $date);
?>

How to create a date from a string?

PHP has a very useful date function called strtotime(). This function converts a human readable date string into a Unix timestamp. If you want to know about Unix time, you can read it from the above section.

strtotime(time, now)

<?php
$date=strtotime("11:00am August 14 2021");
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>

The string accepted by the strtotime function must be correct and valid formatted, otherwise, you will not get the correct in the output. Following are some examples related to the strtotime function.

An example:

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

$d=strtotime("next Friday");
echo date("Y-m-d h:i:sa", $date);

$d=strtotime("+4 Months");
echo date("Y-m-d h:i:sa", $date);
?>

How to get the difference between two dates in php?

The date_diff() method subtracts two valid dates and outputs the difference in the form of a number of days.

<?php
date_diff(datetime1, datetime2, absolute)
?>

The first and second parameters are date objects which will be subtracted and the third parameter is a Boolean. By default, it is set to false. If it is set to true, the difference will be positive.

An example:

<?php
$today=date_create("2021-09-05");
$old_date=date_create("2021-08-12");
$difference=date_diff($today,$old_date);
?>

How to add days, months, years or hours, minutes, and seconds to date in PHP?

If you are a PHP developer, you might have had a situation where you needed to add some time or date in another date object. For this PHP provides us with the date_add function.

Date objectSpecifies a DateTime object returned by date_create()
IntervalSpecifies a DateInterval object
<?php
$date_to_be_added=date_create("2021-09-15");
date_add($date_to_be_added,date_interval_create_from_date_string("10 days"));
echo date_format($date,"Y-m-d");
?>

Q&A

Q: What is the function to get the current date and time in PHP?
A: The function to get the current date and time in PHP is “date()”.

Q: How do I format the date and time using the “date()” function?
A: The “date()” function takes one required parameter, which is a string containing format codes. These codes represent different parts of the date and time, such as the year, month, day, hour, minute, and second. For example, to display the current date and time in the format “Y-m-d H:i:s”, you would use the following code: echo date(“Y-m-d H:i:s”);

Q: Can I set the time zone when using the “date()” function?
A: Yes, you can set the time zone when using the “date()” function by using the “date_default_timezone_set()” function. For example, to set the time zone to Pacific Standard Time, you would use the following code: date_default_timezone_set(‘America/Los_Angeles’);

Q: Is there a way to calculate the difference between two dates in PHP?
A: Yes, you can use the “DateTime” class to calculate the difference between two dates. For example, to calculate the difference between the current date and time and a future date and time, you would use the following code: $current_date = new DateTime(); $future_date = new DateTime(‘2022-12-31’); $diff = $current_date->diff($future_date); echo $diff->format(‘%R%a days’);

Q: How do I get timestamp of a specific date and time in PHP?
A: You can use the function strtotime() to get the timestamp of a specific date and time. For example, to get the timestamp of the date ‘2022-12-31’, you would use the following code: $date = ‘2022-12-31’; $timestamp = strtotime($date);

Q: How do I convert timestamp to date and time format in PHP?
A: You can use the function date() to convert timestamp to a date and time format. For example, to convert timestamp to ‘Y-m-d H:i:s’ format, you would use the following code: $timestamp = 1609459200; $date = date(‘Y-m-d H:i:s’, $timestamp);

Exercises:

  1. How do you get the current date and time?
  2. How do you format a date and time?
  3. How do you calculate the difference between two dates?
  4. How do you convert a timestamp to a date and time?
  5. How do you get the timestamp of a specific date and time?
  6. How do you get the number of days in a month?
  7. How do you check if a year is a leap year?
  8. How do you get the current time zone?

Answers:

  1. The current date and time can be obtained using the date() function. For example: date(“Y-m-d H:i:s”);
  2. The date and time can be formatted using the date() function and specifying the format parameter. For example: date(“m-d-Y H:i:s”, time());
  3. The difference between two dates can be calculated using the strtotime() function and subtracting the timestamps of the two dates. For example: $diff = strtotime(“2022-01-01”) – strtotime(“2021-01-01”);
  4. A timestamp can be converted to a date and time using the date() function and specifying the timestamp as the second parameter. For example: date(“Y-m-d H:i:s”, 1609459200);
  5. A timestamp of a specific date and time can be obtained using the strtotime() function. For example: strtotime(“2022-01-01”);
  6. The number of days in a month can be obtained using the cal_days_in_month() function. For example: cal_days_in_month(CAL_GREGORIAN, 2, 2022);
  7. A year can be checked if it is a leap year using the date() function and specifying “L” as the format parameter. For example: date(“L”, strtotime(“2022-01-01”));
  8. The current time zone can be obtained using the date_default_timezone_get() function.

To read more about the time and date functions in the latest PHP 8 version, please refer to the official PHP 8 page.

How do I get the current date and time in PHP?
Get the current date given a timezone in PHP?
Convert timestamp to time ago in PHP?
Convert a date format in PHP
How do I use PHP to get the current year?
Correctly determine if the date string is a valid date in that format
Convert timestamp to readable date/time PHP
Converting string to Date and DateTime

Iterables in PHP
Introduction to MySQL/PHP

Stay up-to-date about PHP!

We don’t spam!

en English
X
Scroll to Top