How to handle date and time with PHP

in #utopian-io7 years ago (edited)

What Will I Learn?

How to handle date and time with PHP

Requirements

  • PHP

Difficulty

  • Basic

Tutorial Contents

  • UNIX Timestamp
  • Converting UNIX Time To Readable Time
  • Tip For Using The date() Function
  • How To Display Dates Like 'x days ago'?

How to handle date and time with PHP

When I started with PHP, I was a bit confused about this subject so this will hopefully help a beginner a lot.

UNIX TimestampUNIX Timestamp (or Unix time or POSIX time) is the number of seconds since the midnight of January 1, 1970 UTC.

You can get the current timestamp with PHP's time() function:

<strong><?php</strong><br>
    echo time();<br>
<strong>?></strong>

This will show you the number of seconds since January 1, 1970 UTC.

Assume that you are creating a blogging application using PHP and you want to save the time/date of the posts
with them, in your database, you can create a table like this:

<strong>CREATE</strong> <strong>TABLE</strong> <strong>IF</strong> <strong>NOT</strong> <strong>EXISTS</strong> `post` (<br>
 `id` int(10) <strong>UNSIGNED</strong> <strong>NOT</strong> <strong>NULL</strong> <strong>AUTO_INCREMENT</strong>,<br>
 `user_id` int(10) <strong>UNSIGNED</strong> <strong>NOT</strong> <strong>NULL</strong> <strong>DEFAULT</strong> '0',<br>
 `title` varchar(250) <strong>NOT</strong> <strong>NULL</strong> <strong>DEFAULT</strong> '',<br>
 `body` text <strong>NULL</strong> <strong>DEFAULT</strong> '',<br>
 `ip_address` varchar(30) <strong>NOT</strong> <strong>NULL</strong> <strong>DEFAULT</strong> '',<br>
 `date` int(11) <strong>DEFAULT</strong> <strong>NULL</strong>,<br>
 `last_update` int(11) <strong>NOT</strong> <strong>NULL</strong> <strong>DEFAULT</strong> '0',<br>
 <strong>PRIMARY</strong> <strong>KEY</strong> (`id`),<br>
 <strong>KEY</strong> `date` (`date`),<br>
 <strong>KEY</strong> `last_update` (`last_update`)<br>
);

Now, a query to insert a blog post will look something like this:

<strong><?php</strong><br>
<br>
$query = '<br>
    INSERT INTO post<br>
        (<br>
            user_id,<br>
            title,<br>
            body,<br>
            ip_address,<br>
            date,<br>
            last_update<br>
        )<br>
    VALUES<br>
        (<br>
            ' .$user_id .',<br>
            ' .mysql_real_escape_string($_POST['title']) .',<br>
            ' .mysql_real_escape_string($_POST['body']) .',<br>
            ' .mysql_real_escape_string($_SERVER['REMOTE_ADDR']) .',<br>
            ' .time() ',<br>
            ' .time() '<br>
        )<br>
';<br>
<strong>?></strong>

(I left our details about filtering $_POST array out of this, you might want to filter the $_POST array a bit)

This way the query to get all the posts, sorted by date would look like:

<strong>SELECT</strong> *<br>
<strong>FROM</strong> post<br>
<strong>ORDER</strong> <strong>BY</strong> date <strong>DESC</strong>

A query to get all the posts from last 24 hours would look like:

<strong><?php</strong><br>
$start_date = time() - (24 * 60 * 60);<br>
$query = "<br>
 SELECT *<br>
 FROM post<br>
 WHERE date >= <strong>$start_date</strong><br>
 ORDER BY date DESC<br>
";<br>
$result = mysql_query($query);<br>
<em>/* ... */</em><br>
<strong>?></strong>

A Performance Tip: If you don't pay attention, you will end up with 100s of calls to time() throughout your application and we know that function calls have overhead so what do you do?We can call time only ONCE and save the results in a constant which will be global also, just like the time()
function:

<strong><?php</strong><br>
    define('TIME_NOW', time());<br>
<strong>?></strong>

Converting UNIX Time To Readable Time

How do we show what time it is? That is in a format like: Mon, 12 Mar 2018 15:12:46

There is another useful function in PHP for this purpose and that is the date() function.

First you must set a default system timezone, it's very simple, way on top of your scripts, (in your main include
fine perhaps) call this:

<strong><?php</strong><br>
    date_default_timezone_set('EST');<br>
<strong>?></strong>

Don't worry if you don't understand what's happening, this might help clear out a bit of the confusion:
http://www.php.net/manual/en/function.date-default-timezone-set.php

Again, read on and just add the line above on top of your script…Now back to business, here is a simple call to the date() function:

<strong><?php</strong><br>
    echo date('D/M/Y', TIME_NOW); <em>/* TIME_NOW was explained earlier in this same post */</em><br>
<strong>?></strong>

This will show you something like: Sun/Mar/2018

You can see that the first argument is a format in which you want the date to be, shown and the second argument is the timestamp of the date, if you don't provide the second argument, the current timestamp will be used.

Here is another example that shows the time also:

<strong><?php</strong><br>
    echo date('D/M/Y h:i:s A', TIME_NOW); <em>/* TIME_NOW was explained earlier in this same post */</em><br>
<strong>?></strong>

Output: Sun/Mar/2018 03:12:46 PM

These are some more examples:

<strong><?php</strong><br>
<em>// set the default timezone to use.</em><br>
date_default_timezone_set('UTC');<br>
<br>
<br>
<em>// Prints something like: Monday</em><br>
echo date("l");<br>
<br>
<em>// Prints something like: Monday 8th of February 2018 03:12:46 PM</em><br>
echo date('l jS \of F Y h:i:s A');<br>
<strong>?></strong>

I suggest that you read this page:http://php.net/manual/en/function.date.php

Tip For Using The date() Function

You shouldn't have lines like:

<strong><?php</strong><br>
    echo date('D/M/Y h:i:s A', TIME_NOW); <em>/* TIME_NOW was explained earlier in this same post */</em><br>
<strong>?></strong>

All over your code, why?Because if you decide to change the way you show date, then you have to go around and edit all the lines containing:

<strong><?php</strong><br>
    echo date('D/M/Y h:i:s A', TIME_NOW); <em>/* TIME_NOW was explained earlier in this same post */</em><br>
<strong>?></strong>

To fix this, you could have a constant containing your date format string like:

<strong><?php</strong><br>
    define('DATE_FORMAT', 'D/M/Y h:i:s A');<br>
<strong>?></strong>

Then in your code, you do this:

<strong><?php</strong><br>
    echo date(DATE_FORMAT, TIME_NOW);<br>
<strong>?></strong>

Now if you want to change the format of the date throughout your PHP application, you can just edit the line with:

<strong><?php</strong><br>
    define('DATE_FORMAT', 'D/M/Y h:i:s A');<br>
<strong>?></strong>

And it will magically change all of them!Better yet, I would have a function like:

<strong><?php</strong><br>
<br>
    <strong>function</strong> display_date($timestamp = <strong>NULL</strong>) {<br>
        echo date('D/M/Y h:i:s A', $timestamp);<br>
    }<br>
<br>
<strong>?></strong>

Or even better yet, you could have the function return the string as a value, so you have even greater control:

<strong><?php</strong><br>
<br>
    <strong>function</strong> get_date_string($timestamp = <strong>NULL</strong>) {<br>
        return date('D/M/Y h:i:s A', $timestamp);<br>
    }<br>
<br>
<strong>?></strong>

Then call it like:

<strong><?php</strong><br>
    echo get_date_string(TIME_NOW);<br>
<strong>?></strong>

The Pain Of Finding Out The Timestamp From A Formatted Date String

I made the pain part up, fortunately there is a function that does this very easily, it is strtotime()

<strong><?php</strong><br>
    echo strtotime('3/14/2018 02:28:30 PM');<br>
<strong>?></strong>

And bam! magically, you will get the timestamp, it doesn't end there, you can do things like this:

<strong><?php</strong><br>
    echo strtotime('today'), "<strong>\n</strong>";<br>
    echo strtotime('today + 1 day'), "<strong>\n</strong>";<br>
    echo strtotime("now"), "<strong>\n</strong>";<br>
    echo strtotime("14 March 2018"), "<strong>\n</strong>";<br>
    echo strtotime("+1 day"), "<strong>\n</strong>";<br>
    echo strtotime("+1 week"), "<strong>\n</strong>";<br>
    echo strtotime("+1 week 2 days 4 hours 2 seconds"), "<strong>\n</strong>";<br>
    echo strtotime("next Thursday"), "<strong>\n</strong>";<br>
    echo strtotime("last Monday"), "<strong>\n</strong>";<br>
<strong>?></strong>

Read more about strtotime() here:http://php.net/manual/en/function.strtotime.php

How To Display Dates Like 'x days ago'?

I got this function form one of the comments on PHP documentation, it's very nice and does just this:

<strong><?php</strong><br>
    <strong>function</strong> date_range($timestamp) {<br>
        if( $timestamp < 1 ) return '';<br>
        $difference = time() - $timestamp;<br>
        $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");<br>
        $lengths = array("60", "60", "24", "7", "4.35", "12", "10");<br>
        for($j = 0; $difference >= $lengths[$j]; $j++)<br>
        $difference /= $lengths[$j];<br>
        $difference = round($difference);<br>
        if($difference != 1) $periods[$j].= "s";<br>
        $text = "<strong>$difference</strong> <strong>$periods</strong>[<strong>$j</strong>] ago";<br>
        return $text;<br>
    }<br>
<strong>?></strong>

And call it like:

    echo date_range(strtotime('today - 1 day'));<br>
<strong>?></strong>

Back To The Blog Post Example

I will show you a quick example of displaying those blog posts we talked about in the beginning of this tutorial with a nice formatted time:

<strong><?php</strong><br>
$start_date = time() - (24 * 60 * 60);<br>
$query = "<br>
 SELECT *<br>
 FROM post<br>
 WHERE date >= <strong>$start_date</strong><br>
 ORDER BY date DESC<br>
";<br>
$result = mysql_query($query);<br>
while ($post = mysql_fetch_assoc($result)) {<br>
    echo "<strong><strong>{$post['title']}</strong></strong><br />";<br>
    echo "<strong>{$post['body']}</strong><br />";<br>
    echo "Published: " .date_range($post['date']) ."<br /><br />";<br>
}<br>
<strong>?></strong>

This is very simplistic but demonstrates the concept. I hope this helps. If you liked it, help spread the word, it's always appreciated. Good Luck



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Your contribution cannot be approved because it does not follow the Utopian Rules, and is considered as plagiarism. Plagiarism is not allowed on Utopian, and posts that engage in plagiarism will be flagged and hidden forever.

You should've been banned for plagiarism earlier, so you should not have been able to post this (which is more than likely also plagiarised) in the first place.

You can contact us on Discord.
[utopian-moderator]

You better should use DateTime and DateInterval instead of date() and time() ...

Coin Marketplace

STEEM 0.19
TRX 0.15
JST 0.029
BTC 63156.23
ETH 2560.33
USDT 1.00
SBD 2.83