Dates and how much work they can be PDF Print E-mail
User Rating: / 0
PoorBest 
PHP - Basics
Written by Stuart Duncan   
Monday, 19 October 2009 12:41

So you've mastered the variables, made some functions and have files included where you need them... but now you want to add the date to your page. PHP comes with some premade functions which do a lot of the work for us but you'll find that once you go beyond simply displaying today's date, it can get very complicated very fast. Especially if you're trying to deal with dates that look like this: 1255974167

I am going to show you a few things to help take some of the complexity out of it.

 

Why exactly is it that a date shows up as a big number? Well, you can look at it as either brilliant or stupid... but back when the guys who made PHP were putting everything together, they decided that there were no computers around before December 31, 1969... so that was a safe reference point to make as "the start of time"... so to speak.

 

So when you see a number like this '1255974167', that is actually the number of seconds since it was December 31, 1969... and thus, you get an exact time, to the second... although, if your server's clock is set wrong, you're in trouble. Your seconds will be off.

There are 3 premade functions that you will need to know:

  • date()
  • time()
  • mktime()

These functions each do very different operations but they all work together and if you want to be figuring out the number of days between two dates, or figuring out what is happening in the next week... you'll have to know how to work them properly.

date()

The date() function is simply a formatting function... that is to say, no one knows what day or time it is by looking at 1255974167. So we use date() to make it look like something that you and I would recognize.

For example, if we want to see what the date is, we can do date('M d, Y') and we will get something like Oct 19, 2009. Much easier to read, right? If the date is given to us in the form of a big number of seconds, we can pass that along to get it's date like this: date('M d, Y', 1255974167). This would tell us what day that was.

You can probably figure out that M means to show the short form name of the month, d is day number and Y is 4 digit year... but there is a lot more that you can use. Here is a list:

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 (added in PHP 4.1.0) 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 year number. 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) Example: 654321
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()

That should give you just about anything you'd need as far as displaying date/time information to the user.

 

time()

As I said earlier, this simply returns the number of seconds since Dec 31, 1969... which by itself is semi useless a lot of the times, but with a little basic math, you can start to manipulate what the user will see. For example: time() + (7 * 24 * 60 * 60); would give you the date and time exactly 1 week from now.

Use this in combination with the date() function and you can give the user something nicer to look at:

<?php
$nextweek = time() + (7 * 24 * 60 * 60);
echo date('M d, Y H:i:s', $nextweek);
?>

Give it a try.

 

mktime()

This function is where a lot of the magic really happens... this function accepts hours, minutes, seconds, days, months and years.... and spits out a number (the number of seconds since Dec 31, 1969). So if we know someone's birthday right down to the second, we can plug in all that information and get a useable number back that we can format for the page.

This is what you would enter for 8am on Christmas morning:

<?php
$presents_time = mktime(8, 0, 0, 12, 25, 2009);
echo date('Y-m-d H:i:s', $presents_time);
?>

The result is 2009-12-25 8:00:00

This also gives you the ability to do more calculating without having to use your fingers and toes. Let's continue with adding one week to the date, we can do something like this:

<?php
$nextweek = mktime( date('H'), date('i'), date('s'), date('m'), date('d') + 7, date('Y');
echo date('Y-m-d H:i:s', $nextweek);
?>

As you can see, just telling it to add 7 makes things way easier than (7 * 24 * 60 * 60). So long as you remember the pattern of hours, minutes, seconds, month, day, year... you can add or subtract as much as you wish in any area. And if it's the 26th, and you add 7 days, it will just handle all the math on it's own to figure out what day it is in the next month... and display everything properly... even accounting for leap years!

 

My Working Example

Here is a function that I cooked up for a project of mine, to give you a neat idea of how this can be worked:

function dateFormat($x = '', $format = 'M d, Y', $override = false){

// If not numeric, then it's already in date format... so make it numeric
if( !is_int($x) ){ $x = strtotime($x); }

// If ovverride is true, then don't show 'today' 'tomorrow' as dates
if( !$override ){
$dayAfterToday = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d')+1, date('Y')));
$dateAfterX = date('Y-m-d', mktime(0, 0, 0, date('m',$x), date('d',$x), date('Y',$x)));

// If today!
if( date('Y-m-d') == date('Y-m-d', $x) ) return 'Today';
if( $dayAfterToday == $dateAfterX ) return 'Tomorrow';
}

// Return the date inthe format provided
return date($format, $x);
}

This looks pretty complicated but really it's not... I'll explain it piece by piece.

First, you call this function with something like this: dateFormat(time(), 'Y-m-d H:i:s', false);. You can use any date in the first part, time() tells it to work with the date/time right now... next is the format that we want the date returned in, in this case something like 2009-10-19 and then finally, whether or not to override the "Today" and "Tomorrow" responses.

The first part checks to see if the date/time is a number. If it is, it is fine to work with as PHP likes those big numbers of seconds. If not, it uses a premade PHP function that converts a string to a time... hense, strtotime().  So if someone gave you 2009-10-19, it would be able to change that to a big number of seconds.

The next part checks to see if override is false. If it is, then it will check to see if the date it's using is today or tomorrow. If override is true, then it just skips all that to the return part of the function.

If override is false, then it sets a variable to find out what the date is tomorrow, and what the date is of $x at midnight...  notice it's 0, 0, 0 in there? That's midnight. Since the date passed into the function could be any time of the day, we need to use the same time of day to know whether or not the date passed matches tomorrow's date.

Next it does the comparisons to see if date('Y-m-d') (today) equals date('Y-m-d', $x) (date passed to function)... if they are a match, it's Today!! So it returns the word, 'Today'.

The next comparison checks to see if the 2 variables match... tomorrow and the date passed at midnight.  If they match, then it returns the word 'Tomorrow'.
If neither condition is met, it just returns the date in the format that you told it to when you called the function... the default being 'M d, Y'. I use this function a lot for returning a list of people's birthdays. It's a much bigger hint to someone when it says someone's birthday is Tomorrow, instead of just some numbers if they're already not certain what day it is.

 

Conclusion

Don't feel bad if it feels complicated or confusing... working with dates in any programming language can be one of the most tricky aspects to master. Many very very good programmers still struggle with making working calendar simply because working with dates can be so tough. But again, practice is what will get you there.

Copy the functions and examples you've read here and try them out... change some numbers, don't worry about breaking anything.  Unless you're pretty amazing, you likely won't master doing all this date stuff over night. But if you use PHP for more than simply including headers and footers, you will need to know how to format and use dates sooner or later.

Keep practicing!

 

Add comment


Security code
Refresh

Login to TyCamTech.com

Donate

Must have Pepsi, feed my addiction here:


Recommended Books

Learn PHP in 17 hours!
If you can copy and paste into HTML and you can follow simple instructions...

How To Flip Websites Home Study Course.
Complete Video Instruction On How To Quickly Set And And Flip (i.e. Sell) Websites For Profit. 6 X Video Lessons Plus Bonuses -- Great Value For Buyer And Maximum 75% Payout For Affiliate!

Setting up a Web Server
Teaches All The Steps To Hosting A Website From Home.

Follow us on



Follow tycamtech on Twitter