Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. PHPBeginner - UNIX Time, time(), and date()

UNIX Time, time(), and date() - Images: Japanese

Hey there, everyone. Hope you're doing well!

We've covered a lot of ground so far — if statements, comparison operators, switch statements, and more. So this time, let's put all of that together and build a program that displays a message based on what time the page is accessed. I'm calling it "A Day in the Life of Some Guy."

First, let me introduce two functions for working with time: time(), which retrieves the current time, and date(), which converts that time into a human-readable format. The UNIX time returned by time() gets passed into date() for conversion.

UNIX time (also called Unix timestamp) is a system used in computers to represent time as the number of seconds elapsed since January 1, 1970, 00:00:00 UTC.

It's a concept implemented in virtually every OS and programming language, and it's the go-to way to handle time-based processing.

One thing to note is that some languages return the time in milliseconds rather than seconds, so keep that in mind depending on what you're working with.

In PHP, time() returns the value in seconds.

Here's a simple sample using time(). Let's store the result in a variable.

<?php
$time = time();

var_dump($time);

Running this gives you something like:

int(1442029244)

This article was written around noon on September 12, 2015, and 1442029244 is the UNIX time for that moment. That's what time() gives you. Also worth noting: see how it says int? It's a numeric type, so you can use it directly in arithmetic operations.

UNIX time is great for computer processing, but pretty unreadable for humans. That's where date() comes in — let's convert it into a familiar date format.

<?php
$time = time();

echo date('Y/m/d H:i:s', $time);

Running this gives you:

2015/09/12 13:15:06

Much more readable now.

If the time output by date() seems off, your PHP timezone setting may not be set to your local timezone.

In that case, open php.ini in a text editor and set date.timezone to your timezone — for example, "America/New_York" or "Europe/London". That will correct the displayed time.
See this article for details on php.ini.

date.timezone = "America/New_York"

After editing php.ini, you'll need to restart your web server software (like MAMP) for the changes to take effect. Don't forget that step!

Now let's look at how date() actually works. In the first argument, you specify the output format — and you may have noticed some odd-looking letters like Y, m, d, and so on.

echo date('Y/m/d H:i:s', $time);

These letters are called format characters. When you put a recognized format character in the first argument, date() replaces it with the corresponding time value. Any characters that aren't recognized format characters are output as-is.

For example, the letter Y is the format character for a 4-digit year. So if you write just Y as the first argument, the Y gets replaced with the year.

<?php
$time = time();

echo date('Y', $time); // Outputs something like '2015'.

If you write Year: Y, the Y gets replaced with the year while Year: is output as-is, giving you something like Year: 2015.

<?php
$time = time();

echo date('Year: Y', $time); // Outputs something like 'Year: 2015'.

If you want to output a format character as a literal character without converting it, use \ to escape it.

<?php
$time = time();

echo date('\Y', $time); // Outputs the literal letter 'Y'.

m is month, d is day, H is hour (24-hour), i is minute, and s is second. So Y/m/d H:i:s gives you something like 2015/09/12 13:15:06.

date() supports many more format characters — check out the official PHP reference for the full list.

http://php.net/manual/en/function.date.php

By the way, if you just want to output the current time with date(), you can omit the second argument entirely.

<?php
echo date('Y/m/d H:i:s'); // Omitting the second argument outputs the current date and time.

Keep this form in mind too.

Now that we know how to output the current time, let's make it more interesting and build a website that changes its content based on the time of day — "A Day in the Life of Some Guy." Let's start with a bare HTML5 skeleton.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A Day in the Life of Some Guy</title>
</head>
<body>
<!-- PHP goes here -->

</body>
</html>

Let's start by outputting an opening and closing p tag with PHP.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A Day in the Life of Some Guy</title>
</head>
<body>
<?php
    echo '<p>';

    echo '</p>';
?>
</body>
</html>

Next, let's make the text red in the morning and blue in the afternoon. For red we output <p style="color: red"> and for blue <p style="color: blue">, so we can use an if statement together with time() and date() to build it like this:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A Day in the Life of Some Guy</title>
</head>
<body>
<?php
    $time = time(); // Store the access time as UNIX time in a variable.

    if(intval(date('H', $time)) < 12) echo '<p style="color: red">'; // Output the opening p tag depending on AM or PM.
    else echo '<p style="color: blue">';

    echo '</p>'; // Output the closing p tag for the access time.
?>
</body>
</html>

Take a closer look at the part where we call 'time()' and store the result in a variable. The reason we do this is that the value returned by 'time()' keeps changing moment to moment, so we need to capture it once and lock it in a variable. It also avoids calling the function multiple times, which is a nice efficiency win.

Now look at the condition inside the if statement's (): intval(date('H', $time)) < 12. To check whether it's morning, we need to see if the hour from date('H', $time) is less than 12 — so date('H', $time) < 12 would do the job. But it's wrapped in intval(). What's that about?

intval() is a function that converts a string to an integer. For example, intval('1') converts the string 1 to the number 1. Since date() returns its output as a string, we need to convert it to a number before comparing — hence intval(date('H', $time)) < 12. Note that the H format character returns values from 00 to 23 as strings.

In PHP, comparing a numeric string with a pure integer actually works as a numeric comparison, so intval() isn't strictly necessary here.

That said, building your code so that types are always properly matched before comparing helps reduce the chance of unexpected bugs when PHP itself gets updated. It's a good habit to align types explicitly like this before doing comparisons.

intval() converts the numeric portion of the string in its first argument to an integer type. It even handles mixed strings like the following, extracting just the leading number and converting it:

<?php
echo intval('12hoge3'); // Outputs the integer '12'.

That said, this is pretty confusing behavior, so you'd rarely want to do it intentionally.

You can also produce hexadecimal values by prefixing the first argument with 0x or 0X, or by passing the integer 16 as the second argument. When using the second argument, the first argument must be a string; if the conversion fails, it returns 0. The 0x / 0X prefix form uses an integer literal (not a string), so be careful.

<?php
echo intval('hoge');    // If the value can't be converted, returns '0'.
echo intval(0xFF);      // Outputs '255'.
echo intval(0XFF);      // Outputs '255'.
echo intval('0XFF');    // Passing '0X' as a string doesn't work — returns '0'.
echo intval('FF', 16);  // Outputs '255'.
echo intval([]);        // Passing an empty array returns '0'.
echo intval([1, 2]);    // Passing a non-empty array returns '1'.

You can generate octal values and others too, but since PHP doesn't see much use of non-decimal bases in practice, you don't need to memorize all of this.

Decimal (base 10) means numbers that carry over at 10 — the system you use every day.

Binary (base 2) uses only 0 and 1, carrying over at 2. Hexadecimal (base 16) uses 0–9 and A–F, carrying over at 16.

You've probably seen RPGs where character stats max out at 255. That's because the maximum value of a two-digit hexadecimal number — FF — converts to 255 in decimal.

To convert decimal to binary, you divide by 2 repeatedly until the quotient reaches 0, then read the remainders in reverse order. But honestly, it's easier to just let a computer or calculator do it. Same goes for hexadecimal.

These days, with modern hardware being so powerful, binary and hexadecimal don't come up as often as they used to.

Now that we have the text color changing based on AM/PM, let's also output the access time.

We can use date() to format the time however we like.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A Day in the Life of Some Guy</title>
</head>
<body>
<?php
    $time = time(); // Store the access time as UNIX time in a variable.

    if(intval(date('H', $time)) < 12) echo '<p style="color: red">'; // Output the opening p tag depending on AM or PM.
    else echo '<p style="color: blue">';

    echo 'Access time: ' . date('H:i:s', $time); // Output the access time.

    echo '</p>'; // Output the closing p tag for the access time.
?>
</body>
</html>

Now let's add some messages for each hour of the day. We'll use a switch statement here for practice (using the strict-comparison pattern).

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A Day in the Life of Some Guy</title>
</head>
<body>
<?php
    $time = time(); // Store the access time as UNIX time in a variable.

    if(intval(date('H', $time)) < 12) echo '<p style="color: red">'; // Output the opening p tag depending on AM or PM.
    else echo '<p style="color: blue">';

    echo 'Access time: ' . date('H:i:s', $time); // Output the access time.

    echo '</p>'; // Output the closing p tag for the access time.

    echo '<p>'; // Output the opening p tag for the message.

    switch(true){ // Switch message based on the current hour.
        case intval(date('H', $time)) <= 7:
            echo '...';
            break;
        case intval(date('H', $time)) <= 8:
            echo 'Finally awake. A bit hungover but nothing too serious. Pushing too hard right out of the gate might cause a burnout later. Best to focus on waking up properly with some coffee first. Going all-out starting at 9.';
            break;
        case intval(date('H', $time)) <= 10:
            echo '...';
            break;
        case intval(date('H', $time)) <= 11:
            echo 'Oops. Started watching videos and a few hours just vanished. But it\'s still not time to panic. Going all-out starting at 12.';
            break;
        case intval(date('H', $time)) <= 12:
            echo 'The world is having lunch right now. Getting hungry myself. Missing a clean round number like 12:00 is a shame, but staying in sync with the rest of society is important. The day is still long. Let\'s get lunch sorted. Going all-out starting at 13.';
            break;
        case intval(date('H', $time)) <= 14:
            echo '...';
            break;
        case intval(date('H', $time)) <= 15:
            echo 'Oops. Ate too much and somehow dozed off. Jumping straight into work after waking up isn\'t great for the body though. The day is still long. Going all-out starting at 16.';
            break;
        case intval(date('H', $time)) <= 16:
            echo 'Still feeling groggy from that nap. Pushing through when it won\'t do any good is pointless — better to bide my time. The night is still young. Going all-out starting at 17.';
            break;
        case intval(date('H', $time)) <= 20:
            echo '...';
            break;
        case intval(date('H', $time)) <= 21:
            echo 'Oops. Got absorbed in a game and now it\'s this late. Could still get things done at this hour, but the world is having dinner right now. Staying in sync with society is important. Let\'s get dinner out of the way first. Going all-out starting at 22.';
            break;
        case intval(date('H', $time)) <= 23:
            echo 'Oops. Started drinking beer and now it\'s this late. Today just didn\'t work out — no opportunities came my way. Feeling pretty bummed, so I\'ll go post "what a productive day" online. Going all-out starting tomorrow.';
            break;
    }
    echo '</p>';
?>
</body>
</html>

Note that the sample above uses a switch statement for practice purposes.

As covered in the previous article, when you need strict-comparison branching in PHP, using an if statement is the more common approach — just keep that in mind.

We've got a program that changes its text based on the access time.

Once you've tested it and confirmed it works, there's actually one thing left to clean up.

Look at the intval(date('H', $time)) calls in the switch statement.

Even though we need the same value multiple times, intval(date('H', $time)) is written out in full every time. That means intval() and date() are being called over and over needlessly — not exactly efficient.

When you're using the same value repeatedly like this, what's the smart move? Right — store it in a variable. Let's put the result of intval(date('H', $time)) into a well-named variable and use that variable throughout. Here's the finished version:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A Day in the Life of Some Guy</title>
</head>
<body>
<?php
    $time = time(); // Store the access time as UNIX time in a variable.
    $int_h = intval(date('H', $time)); // Store values you'll use multiple times in a variable.

    if($int_h < 12) echo '<p style="color: red">'; // Output the opening p tag depending on AM or PM.
    else echo '<p style="color: blue">';

    echo 'Access time: ' . date('H:i:s', $time); // Output the access time.

    echo '</p>'; // Output the closing p tag for the access time.

    echo '<p>'; // Output the opening p tag for the message.

    switch(true){ // Switch message based on the current hour.
        case $int_h <= 7:
            echo '...';
            break;
        case $int_h <= 8:
            echo 'Finally awake. A bit hungover but nothing too serious. Pushing too hard right out of the gate might cause a burnout later. Best to focus on waking up properly with some coffee first. Going all-out starting at 9.';
            break;
        case $int_h <= 10:
            echo '...';
            break;
        case $int_h <= 11:
            echo 'Oops. Started watching videos and a few hours just vanished. But it\'s still not time to panic. Going all-out starting at 12.';
            break;
        case $int_h <= 12:
            echo 'The world is having lunch right now. Getting hungry myself. Missing a clean round number like 12:00 is a shame, but staying in sync with the rest of society is important. The day is still long. Let\'s get lunch sorted. Going all-out starting at 13.';
            break;
        case $int_h <= 14:
            echo '...';
            break;
        case $int_h <= 15:
            echo 'Oops. Ate too much and somehow dozed off. Jumping straight into work after waking up isn\'t great for the body though. The day is still long. Going all-out starting at 16.';
            break;
        case $int_h <= 16:
            echo 'Still feeling groggy from that nap. Pushing through when it won\'t do any good is pointless — better to bide my time. The night is still young. Going all-out starting at 17.';
            break;
        case $int_h <= 20:
            echo '...';
            break;
        case $int_h <= 21:
            echo 'Oops. Got absorbed in a game and now it\'s this late. Could still get things done at this hour, but the world is having dinner right now. Staying in sync with society is important. Let\'s get dinner out of the way first. Going all-out starting at 22.';
            break;
        case $int_h <= 23:
            echo 'Oops. Started drinking beer and now it\'s this late. Today just didn\'t work out — no opportunities came my way. Feeling pretty bummed, so I\'ll go post "what a productive day" online. Going all-out starting tomorrow.';
            break;
    }
    echo '</p>';
?>
</body>
</html>

See the sample here.

That was a longer one, but that's all for this article. It was a bit of a silly program, but I hope it was useful. Changing website content based on the time of day is a fundamental technique in dynamic web development — hope it gave you something to work with.

In the next article, we'll look at the for loop for repeated processing. See you there!

This article was written by Sakurama.

Author's beloved small mammal

桜舞 春人 Sakurama Haruto

A Tokyo-based programmer who has been creating various content since the ISDN era, with a bit of concern about his hair. A true long sleeper who generally feels unwell without at least 10 hours of sleep. His dream is to live a life where he can sleep as much as he wants. Loves games, sports, and music. Please share some hair with him.

If you find any errors or copyright issues, please .