During any PHP and Web Development Project there are times that you need to know what is the date and time, It can be because you are scheduling a task or delaying one, waiting or for what ever reason you need to know the Time and the Date .

In PHP server describes the time and date as a number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) also known as timestamp, in order for us to translate that to our language so clients can understand it we use the date() function to format it to any way that we want here is how:

string date(format , timestamp);

This function will return a String as the result and you will give it format as a String and a timestamp that is optional so if you don’t mention it it will use the current date and time as the timestamp, it will format it according to the format that you setup and then return it as a String.

We tell the function how to return the time and date using the format String and here are a few of the formats you can use:

format String What it Shows?
D Mon, Tue, Wed, Thu, Fri, Sat, Sun
d 00 to 31 ~ Day of the month
M Jan to Dec ~ month using letters
m 01, 02, 03, 04, 05 ,06, 07, 08 ,09, 10, 11, 12 ~ month of the date
Y yyyy ~ for digit year, like 2011 or 1995
y yy ~ two digit year, like 97 or 01
h 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12 ~ hours in 12 hours format
H 01 to 23 ~ hours in 24 hours format
i 00 to 59 ~ minutes of time
s 00 to 59 ~ Seconds of the time
a am or pm
A AM or PM

Here are a few examples:

$timestamp=mktime(0, 0, 0, 7, 1, 2000); // timestamp for 1st of July 2000

$var=date(“D : d/M/Y”,$timestamp);// you can set it to a variable

echo $var;// will show:       Sat : 00/Jul/2000

echo date(“D : d/M/Y ~ h : i : s : A”);// you can directly use it in a function or command this will show which is the current date and time:      Sat : 25/06/2011 ~ 06 : 49 : 53 AM

In order to get the timestamp you can use a function called mktime with this format:

timestamp mktime(hour,minute,second,month,day,year,is_dst);

The options are self explanatory with exception of the last which determines if using Day time saving or not and you can leave it out for default.

You can also use the time function to get the current timestamp, so you can calculate a future or past date here is how:

$var=time();//current timestamp

echo $var;// shows the current time stamp

echo (time()+(24*60*60));// this is the timestamp of tomorrow(24 hours * 60 minutes in each hour * 60 seconds in each minute)

%d bloggers like this: