Broad Network


PHP Local and UTC Time

Date and Time in PHP with Security Considerations - Part 2

Foreword: In this part of the series I explain how to obtain local and UTC time in PHP.

By: Chrysanthus Date Published: 19 Jan 2019

Introduction

This is part 2 of my series, Date and Time in PHP. In this part of the series I explain how to obtain local and UTC time in PHP. When the operating system is installed in your computer, the country or region where you are thought to be living, is saved. From this setting, PHP can get your local time, GMT or UTC time. For some countries, the GM and UTC times are the same. You should have read the previous part of series before reaching here, as this is the continuation.

The Time
PHP considers date and/or time simply as time. It has one structure in which it would place the second, minute, hour, day number of the month, month number, year, week day number, day number of year, and daylight saving indicator, of any particular moment in time. It is up to the programmer to separate conventional date from conventional time or use both as one unit. I explain all that below. The structure is not accessed directly; it is accessed indirectly - see below.

Time Components
Time components are second, minute, hour, day number of the month, month number, year, week day number, day number of year, and daylight saving indicator. The value of each of these is a number.

Local Time
To obtain the local date and time, use the localtime() function as follows:

    localtime(time(), true)

Note the function call, time() as the first argument.

As associative array will be returned with the following elements:

    "tm_sec" - seconds, 0 to 59
    "tm_min" - minutes, 0 to 59
    "tm_hour" - hours, 0 to 23
    "tm_mday" - day of the month, 1 to 31
    "tm_mon" - month of the year, 0 (Jan) to 11 (Dec)
    "tm_year" - years since 1900
    "tm_wday" - day of the week, 0 (Sun) to 6 (Sat)
    "tm_yday" - day of the year, 0 to 365
    "tm_isdst" - is daylight savings time in effect? Positive if yes, 0 if not, negative if unknown.

Try the following code:

<?php

    $arr = localtime(time(), true);

    foreach ($arr as $key => $value)
        echo $key, ' => ', $value, '<br>';

?>

I tried it and I had the following output:

    tm_sec => 12
    tm_min => 6
    tm_hour => 7
    tm_mday => 10
    tm_mon => 0
    tm_year => 119
    tm_wday => 4
    tm_yday => 9
    tm_isdst => 0

Note that in order to get the correct year, you have to add 1900 to tm_year: 119 + 1900 = 2000. In order to get the correct month, you have to add 1 to tm_mon: 1 + 0 = 1.

Formatting Datetime
Timestamp means the components and date and those of time, put is one unit. An example of timestamp is 02-10-25 03:35:15 . In practice, you would need just the time, 03:35:15 or date, 02-10-25 or datetaime, 02-10-25 03:35:15 . These are three different formats of time in PHP.

The function to get the current timestamp is, time(). However, avoid using it directly. In order to get the timestamp in a particular format, you have to use the date() function whose syntax is:

    string date ( string $format [, int $timestamp = time() ] )

If you want localtime, the syntax is:

    string date ( string $format)

Format Parameter of Date Function
To use the $format parameter, you need the following table:

character                     Description                                 Example returned values
Day --- ---
d: Day of the month, 2 digits with leading zeros: 01 to 31
D: A textual representation of a day, three letters: Mon through Sun
j: Day of the month without leading zeros: 1 to 31
l (lowercase 'L'): A full textual representation of the day of the week: Sunday through Saturday
N: ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0): 1 (for Monday) through 7 (for Sunday)
S: English ordinal suffix for the day of the month, 2 characters: st, nd, rd or th. Works well with j
w: Numeric representation of the day of the week: 0 (for Sunday) through 6 (for Saturday)
z: The day of the year (starting from 0): 0 through 365
Week --- ---
W: ISO-8601 week number of year, weeks starting on Monday: Example: 42 (the 42nd week in the year)
Month: --- ---
F: A full textual representation of a month, such as January or March: January through December
m: Numeric representation of a month, with leading zeros: 01 through 12
M: A short textual representation of a month, three letters: Jan through Dec
n: Numeric representation of a month, without leading zeros: 1 through 12
t: Number of days in the given month: 28 through 31
Year --- ---
L: Whether it's a leap year: 1 if it is a leap year, 0 otherwise.
o : ISO-8601 week-numbering year. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0): Examples: 1999 or 2003
Y: A full numeric representation of a year, 4 digits: Examples: 1999 or 2003
y: A two digit representation of a year: Examples: 99 or 03
Time --- ---
a: Lowercase Ante meridiem and Post meridiem: am or pm
A: Uppercase Ante meridiem and Post meridiem: AM or PM
B: Swatch Internet time: 000 through 999
g: 12-hour format of an hour without leading zeros: 1 through 12
G: 24-hour format of an hour without leading zeros: 0 through 23
h: 12-hour format of an hour with leading zeros: 01 through 12
H: 24-hour format of an hour with leading zeros: 00 through 23
i: Minutes with leading zeros: 00 to 59
s: Seconds, with leading zeros: 00 through 59
u: Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds.: Example: 654321
v: Milliseconds (added in PHP 7.0.0). Same note applies as for u: Example: 654
Timezone --- ---
e: Timezone identifier (added in PHP 5.1.0): Examples: UTC, GMT, Atlantic/Azores
I (capital i): Whether or not the date is in daylight saving time: 1 if Daylight Saving Time, 0 otherwise.
O: Difference to Greenwich time (GMT) in hours: Example: +0200
P: Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3): Example: +02:00
T: Timezone abbreviation: Examples: EST, MDT ...
Z: Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive: -43200 through 50400
Full Date/Time --- ---
c: ISO 8601 date (added in PHP 5): 2004-02-12T15:19:21+00:00
r: » RFC 2822 formatted date: Example: Thu, 21 Dec 2000 16:01:07 : +0200
U: Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT): See also time()

Unrecognized characters in the format string will be printed as-is.

Formatting Illustrations
The following code gives time in the format: hours:mins:secs :

<?php

    $str = date('H:i:s');

    echo $str;

?>

The output of my computer was:

    08:11:24

The following code gives the USA date format: month:day:yyyy :

<?php

    $str = date('m-d-Y');

    echo $str;

?>

The output of my computer was:

    01-10-2019

The following code gives a timestamp :

<?php

    $str = date('m-d-Y H:i:s');

    echo $str;

?>

The output of my computer was:

    01-10-2019 08:30:50

Note that when you want a space in the format, you just type the space.

The date() function returns a formatted date string. If a non-numeric value is used for timestamp, FALSE is returned and an E_WARNING level error is emitted.

GMT and UTC
There is a relationship between localtime and GMT or UTC. To obtain the GMT or UTC, use the following function:

    gmdate()

You still have to do formating. Try the following code:

<?php

    $dt = gmdate('M d Y H:i:s');

    echo $dt;

?>

The output of my computer was:

    Jan 10 2019 10:16:42

The gmdate() function returns a formatted date string. If a non-numeric value is used for timestamp, FALSE is returned and an E_WARNING level error is emitted.

The checkdate() Function
This function validates a Gregorian date. The syntax is:

    bool checkdate ( int $month , int $day , int $year )

The function checks the validity of the date formed by the arguments. A date is considered valid if each argument is properly defined.

Parameters

month
    The month is between 1 and 12 inclusive.

day
    The day is within the allowed number of days for the given month. Leap years are taken into consideration.

year
    The year is between 1 and 32767 inclusive.

The function returns TRUE if the date given is valid; otherwise returns FALSE.

Try the following code:

<?php

    if (checkdate(12, 31, 2000))
        echo 'good', '<br>';
    else
        echo 'bad', '<br>';

    if (checkdate(2, 29, 2001))
        echo 'good', '<br>';
    else
        echo 'bad', '<br>';

?>

The output is:

    good
    bad

That is it for this part of the series. We stop here and continue in the next part.

Chrys


Related Links

Basics of PHP with Security Considerations
White Space in PHP
PHP Data Types with Security Considerations
PHP Variables with Security Considerations
PHP Operators with Security Considerations
PHP Control Structures with Security Considerations
PHP String with Security Considerations
PHP Arrays with Security Considerations
PHP Functions with Security Considerations
PHP Return Statement
Exception Handling in PHP
Variable Scope in PHP
Constant in PHP
PHP Classes and Objects
Reference in PHP
PHP Regular Expressions with Security Considerations
Date and Time in PHP with Security Considerations
Files and Directories with Security Considerations in PHP
Writing a PHP Command Line Tool
PHP Core Number Basics and Testing
Validating Input in PHP
PHP Eval Function and Security Risks
PHP Multi-Dimensional Array with Security Consideration
Mathematics Functions for Everybody in PHP
PHP Cheat Sheet and Prevention Explained
More Related Links

Cousins

BACK NEXT

Comments