Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
web development
communitycreator

What is the strtotime() function in PHP?

NDUKWE CHIDERA K.

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

What is the strtotime() function?

The strtotime() function is a built-in function in PHP that converts a date or time-related strings into real date/time objects. This function is so powerful that it can parse virtually any datetime related English text to Unix timestamp.

The Unix timestamp is the number of seconds since January 1, 1970, 00:00:00 UTC.

This function will format a time string into a Unix timestamp relative to the provided baseTimeStamp argument.

Syntax

strtotime($datetime,$baseTimeStamp)

Parameters

  • dateTime: This parameter is any valid English string in the date/time format.
  • baseTimeStamp This parameter will be used as the timestamp to calculate the relative date. This parameter can be omitted and, if omitted, will be assumed to be the current time.

Code

Different English time/date strings are parsed and converted to Unix timestamp they represent using the strtotime() function in the code below.

<?php
echo(strtotime("now") . "<br>");
echo(strtotime("9 October 2021") . "<br>");
echo(strtotime("+2 hours") . "<br>");
echo(strtotime("+4 week") . "<br>");
echo(strtotime("+5 week 10 days 5 hours 30 seconds") . "<br>");
echo(strtotime("next Tuesday") . "<br>");
echo(strtotime("last Friday")). "<br>";
echo(strtotime("tomorrow"));
?>

It may be challenging to make sense of the output above. The code below presents the formatted date strings in a more understandable manner.

<?php
//declare a datetime string
$str = 'tomorrow';
$timestamp = strtotime($str);
// This will check for wrong datetime string
if ($timestamp === false) {
echo "The string ($str) is vague";
} else {
echo "$str is: " . date('l dS \o\f F Y h:i:s A', $timestamp);
}
?>

RELATED TAGS

php
web development
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring