
PHP’s DateTime object is the object-oriented approach to dealing with dates and time zones. Php > print date("r", strtotime("next month", mktime(0, 0, 0))) Php > print date("r", strtotime("next month")) Php > print date("r", strtotime("+1 week")) You can see that mktime() can be very helpful when dealing with database queries that use date ranges customized by a user. For example, if you’re storing timestamps as integers (Unix time) in MySQL (foreshadowing anyone?), it’s very easy to set up a common year-to-date query range. You set isDST to 1 if daylight savings is in effect, 0 if it’s not, and -1 if it’s unknown (the default value). It takes a number of integer arguments to set each part of the date in this order: mktime(hour, minute, second, month, day, year, isDST) Mktime() is used to create a Unix timestamp given a list of values that correspond to each part of a date (seconds, minutes, hours, year, etc). The function becomes more useful though when combined with the mktime() and strtotime() functions, as you’ll see in the coming examples. Php > print date("jS of F Y", $unixTime) įor the entire list of acceptable formatting characters, see the page for date() in the PHP documentation. php > print date("m/d/y h:i:s a", $unixTime) Of course, you can use other specifiers to define your own custom formats. The “r” formatting string returns the time formatted as specified by RFC 2822. If the optional timestamp is not provided, the value of time() is used. date() is used to format Unix timestamps into a human readable string, and takes a formatting argument and an optional time argument. Unix time can be easily formatted into just about any string that a human would want to read. It takes an optional Unix timestamp argument, but defaults to the value of time() if one isn’t provided. If you need an array representation of the Unix time, use the getdate() function. To illustrate this, I will use the PHP interactive CLI shell. Time() takes no arguments and returns the number of seconds since the Unix epoch.

I’ll talk more on this later, but let’s ignore time zone issues for now and look at some time functions. All other time zones in the world are expressed as a positive or negative offsets from this time. Treating time in UTC and Unix time will make your life easier when you need to deal with time zones.
#Php time calculation example full
UTC, also know by its full name Coordinated Universal Time, also referred to as GMT, and sometimes Zulu time, is the time at 0-degrees longitude. If you’re interested in a complete history of Unix time, check out the Unix time article on Wikipedia.

Time is represented as an offset in the amount of seconds that have ticked away since midnight of January 1, 1970, UTC. Much of this article will work with Unix time, or POSIX or epoch time as it is otherwise known.
