jump to navigation

Working with date() and time() in PHP October 28, 2010

Posted by Tournas Dimitrios in PHP.

This article shows you how to work with dates and times in PHP. Web programs often involve an extensive amount of extraction, manipulation, comparison, and display of dates. The task gets more involved when you add MySQL to the mix. But first, let’s talk about the native time format on your server.

How Unix Time Works :
Before going into detail about how to work with dates,an introduction has to made about the basics of how POSIX-compliant Unix/Linux servers (and thus, PHP) keep time.

Midnight, January 1, 1970, is when time “began” for Unix computers. In Unix parlance, that timestamp is 0, and it’s called the epoch date.
Any date since then is calculated as the number of seconds that have elapsed between January 1, 1970, and that time. For example, as I write this at 12:00:21 on october 28 , 2010, 1,288,256,378 seconds have passed since that fabled date. Thus, the timestamp as I write this is  —1288256378.
This scheme makes manipulating dates in PHP relatively easy as long as you don’t need to show the date in a readable format. For example, you can jump ahead a day by adding (60 x 60 x 24) seconds to the current timestamp or go back one hour by subtracting 3,600 seconds. Because the timestamp is just a number and computers can handle numbers with a explicit way , it is handy when comparing adding ,substracting numbers that represend the time .
Because humans don’t understand timestamps very well, whenever you want to print a date, you should use a format to convert to human readable time . PHP supports a bunch of methods to make this work easy for us .See the PHP manual .

To get the current timestamp, call the time() function with no arguments. The return value is the current timestamp on the server. This simple example prints the current time:
echo ‘The current timestamp is ‘ . time();
You can also assign the returned value of the timestamp() function to variables, like so: $time = time();
Many PHP date-related functions take a timestamp argument, and most of them use the current time if you don’t supply that parameter. For example, the date() function returns a formatted date string in a custom format (like Nov 1, 2010), by using the syntax date(“format”, timestamp). But if you don’t give it a timestamp, the default is the current time. This means that for most of the time functions, you don’t even need to include time() as a parameter if you want to work with the current timestamp.
echo date(“D:d F  Y”);  // returns : Thu:28 October 2010

The table below shows all the posible arguments that you can pass to the date() function , so the output can be formated to your needs .

Date Format Character Description Example Returned Values
d Day of the month, two 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
S English ordinal suffix for the day of the month, two 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 0 through 365
W ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0) 42 (the 42nd week in the year)
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
L Represents a leap year 1 if it is a leap year, 0 otherwise
Y A full numeric representation of a year, four digits 1999 or 2003
y A two-digit representation of a year 99 or 03
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 through 59
s Seconds, with leading zeros 00 through 59
Time Zone
I Represents daylight saving time 1 if daylight saving time, 0 otherwise
O Difference from UST in hours +0200
T Time zone setting of this machine EST, MDT, etc.
Z Time zone offset in seconds. The offset for time zones west of UTC is always negative, and is always positive for time zones east of UTC. 43200 through 43200
Full Date/Time
c ISO 8601 date (added in PHP 5) 2008-12-18T16:01:07 +02:00
r RFC 2822 formatted date Thu, 18 Dec 2008 16:01:07 +0200

date() Function Sample Strings :

Date Format String Sample Output
l (lowercase L) Saturday
M Oct
H:m 1:36
G:i:s A 5:26:01 PM
m-d-Y 10-10-2010
M-j-y Jun-1-10
M-d-Y h:m:s a Aug-22-2010 12:08:00 am

Getting the Timestamp of a Date in the Past or Future :

Let’s explore how to determine some other timestamps close to the current time. For example, you can extract yesterday’s timestamp or, say, next Friday’s. There are two general methods for finding these values:

  • Determining the timestamp based on a string
  • Determining the timestamp from date values (which can be a bit trickier)
  1. Creating Timestamps from a String
  2. The strtotime() function can sometimes be a PHP programmer’s best friend. Just as its name suggests, strtotime() generates a timestamp from an English date-phrase, such as April 5 or Friday. These strings can be either relative to the current date or absolute. Table below outlines some of the possibilities.

    Table  strtotime() Examples
    Invocation Output (as a timestamp)
    strtotime("Friday") Friday at midnight
    strtotime("+1 week Friday") The Friday after next at midnight
    strtotime("+1 week") A week from right now
    strtotime("-2 months") Two months ago from right now
    strtotime("October 21, 2010") October 21, 2010, at midnight
    strtotime("2008-10-01") October 21, 2010, at midnight
    strtotime("Friday 12:01 p.m.") Friday at 12:01 PM
    strtotime("+7 days 12:01 p.m.") Seven days from now at 12:01 PM
  3. Creating Timestamps from Date Values

If you know the precise date and time you need, you can create a timestamp with the mktime() function. To use the mktime() function, you need the hour, the minute, the second, the number of the month, the day, and the year of the timestamp you want to create.

For example:

$future_date = mktime($hour, $minute, $second, $month, $day, $year);
Finding the Difference Between Two Dates :

You can use strtotime() to convert two dates to unix time and then calculate the number of seconds between them. From this it’s rather easy to calculate different time periods.

$date1 = "2007-03-24";
$date2 = "2010-10-28";

$diff = abs(strtotime($date2) - strtotime($date1));

$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

printf("%d years, %d months, %d days\n", $years, $months, $days);

Ref :127



No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s