Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

PHP Date and Time – A Beginner’s Guide

INTRODUCTION
THE OVERWHELMING DATE & TIME

Welcome to a beginner’s tutorial on date and time in PHP. I am sure that the date and time are seemingly easy to any beginners. I mean, who does not know there are 24 hours a day, or 365 days in a year? But just after a little bit of experience with PHP, one will soon realize that it is deceptively confusing.

How do we properly Format a date string in PHP? What is the ISO date format? How does that Unix timestamp thing work? How do we work with different time zones? There are simply so many dimensions to date and time that it can be overwhelming. So let us walk through some of these date time basics in this guide – Read on!

I have included a zip file with all the example source code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

CONFESSION
AN HONEST DISCLOSURE

Quick, hide your wallets! I am an affiliate partner of Google, eBay, Adobe, Bluehost, Clickbank, and more. There are affiliate links and advertisements throughout this website. Whenever you buy things from the evil links that I recommend, I will make a commission. Nah. These are just things to keep the blog going, and allows me to give more good stuff to you guys - for free. So thank you if you decide to pick up my recommendations!


 

NAVIGATION
TABLE OF CONTENTS

Section A
The Basics

Section B
Date Time in PHP

Section C
More Examples

Extra
Useful Bits

Extra
Source Code Download

Closing
What’s Next?

SECTION A
THE BASICS

Before we go into any code, let us start with the basic and boring knowledge… Because it is necessary for good code ninjas to know all of these.

ISO DATE FORMAT

When it comes to the date format on the Internet (not just in PHP), there is one ISO standard that you must know – ISO 8601. Well, here is the very compressed version to not bore people to tears:

  • The year must be in the format of yyyy. For example, 1999.
  • Year and month in yyyy-mm. For example, 1999-08.
  • Full date in yyyy-mm-dd. For example, 1999-08-07.
  • To represent the week of the year yyyy-Www. For example, 1999-W12.
  • Date and time are in UTC yyyy-mm-ddThh:mm:ssZ. For example, 1999-08-07T12:34:56Z.
  • To add a time zone yyyy-mm-ddThh:mm:ss+|-hh:mm. For example, 1999-08-07T12:34:56+04:00 or 1999-08-07T12:34:56-02:00.

That’s all for the common date formats. If you like to learn more about ISO 8601, I shall leave some links in the extras section below.

DATE TIME IN DATABASES

Please do take note that not all databases adopt ISO 8601 strictly. For example, MongoDB does adopt the ISO 8601 format quite rigorously, while MySQL only uses a “close enough” format to keep the date/time – yyyy-mm-dd hh:mm:ss (missing the “T” in the middle, and “Z” at the end). To get an ISO 8601 date/time from MySQL, we will need to do some yoga, and we shall walk through some examples below.

UNIX EPOCH TIME (UNIX TIMESTAMP)

This is another mystery you will find quite often in the cyber world, not just in PHP. Long story short, the Unix timestamp is the number of seconds that have elapsed since 1 Jan 1970 00:00:00 UTC. Yeah, it may sound silly and useless to some beginners right now, but it is actually very useful in calculations. For you guys who want to learn more, I will leave a link in the extras section below.

SECTION B
DATE TIME IN PHP

Now that you know the boring basics – Let us dive into the date and time-related functions in PHP, also some examples on how to use them.

TIME

time() is one of the most basic time functions in PHP, and it gives you the current Unix timestamp. 

1a-time.php

If you want to get the time one hour from now:

1b-time.php
";

// 1 hour = 60 mins X 60 seconds = 3600 seconds
$later = $now + 3600;
echo "1 hour later - " . $later;
?>

DATE

To “convert” the Unix Timestamp into human-readable form, we can use the date(FORMAT, TIMESTAMP) function.

2a-date.php

Please feel free to format the date as required, read the full list of how you can format the date here. But a gentle reminder that the timestamp is in UTC, use the date_default_timezone_set function if you need it in another time zone:

2b-timezone.php

You can get the full list of supported Timezones here.

MKTIME

Apart from time(), there is a more… modular way to create Unix Timestamps – mktime(HR, MIN, SEC, MONTH, DAY, YEAR).

3-mktime.php

STRTOTIME

If you prefer a more human way to create the Unix Timestamps, use the strtotime(STRING) function:

4-strtotime.php
";

$timestamp = strtotime("-1 hour");
$human = date("Y-m-d H:i:s", $timestamp);
echo "1 hour before - $human
"; $timestamp = strtotime("yesterday"); $human = date("Y-m-d H:i:s", $timestamp); echo "Yesterday - $human
"; $timestamp = strtotime("2014-03-21 12:34:56"); echo "Date to timestamp - $timestamp
"; ?>

This is probably one of the most useful functions, as it can even convert a date back to a timestamp. Read the PHP manual for the full list of what it can convert.

GET DATE

Lost track of a timestamp? Or only need certain parts of the date for processing? Use the getdate(TIMESTAMP) function:

5-getdate.php

SECTION C
MORE EXAMPLES

Need more examples of how to deal with timestamps in PHP? Here are a couple of common ones.

TIME LOOP

Need to loop through the next couple of days for some calculations? Just use the for loop and good old elbow grease Mathematics.

6-loop.php
";
}
?>

MYSQL TIMESTAMPS

Remember that timestamps are recorded in the format of yyyy-mm-dd hh:mm:ss in MySQL? We can actually use SQL to directly format the timestamp.

7-mysql.php

COMMON DATE FORMATS

Now for some common date formats.

8-common-format.php
";

// In ISO 8601 format
echo date("c", $timestamp) . "
"; // Human friendly form echo date("j F Y, g:ia", $timestamp) . "
"; // Week number echo date("Y", $timestamp) ."-W". date("W", $timestamp) . "
"; ?>

DATE COMPARISON

9-compare.php

DATE DIFFERENCE

10-difference.php
format('%R%a days');
echo "$days difference between $dateA and $dateB";
?>

To compare 2 dates, we can use the date_diff(DATE, DATE) function, check out the PHP manual for a complete list on how to format the difference interval.

EXTRA
USEFUL BITS

That’s all for this project, and here is a small section on some extras that may be useful to you.

SUMMARY – ALL THE COMMON DATE/TIME FUNCTIONS

FunctionDescription
date_default_timezone_set(STRING)Sets the current time zone.
time()Gets the current Unix timestamp.
mktime(HR, MIN, SEC, MONTH, DAY, YEAR)Creates a Unix timestamp from the given time parameters.
strtotime(STRING)Converts a given string into a Unix timestamp.
date(FORMAT, TIMESTAMP)Formats a given timestamp into human-readable form.
getdate(TIMESTAMP)Gets an array of information on the given timestamp.
date_diff(DATE, DATE)Gets the difference between 2 dates.

CHEAT SHEET

Date and Time In PHP (click to Enlarge)

EXTRA REFERENCES

  • ISO 8601 on Wikipedia
  • Date and Time Formats on W3C
  • Unix Epoch Time on Wikipedia

EXTRA
DOWNLOAD

Finally, here is the download link to all the example source code as promised.

SOURCE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
 

CLOSING
WHAT’S NEXT?

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to understand better, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

The post PHP Date and Time – A Beginner’s Guide appeared first on Code Boxx.



This post first appeared on Xxxxxxxxx, please read the originial post: here

Share the post

PHP Date and Time – A Beginner’s Guide

×

Subscribe to Xxxxxxxxx

Get updates delivered right to your inbox!

Thank you for your subscription

×