Wednesday 16 October 2013

php using date and time for various purposes

We always need to deal with date and time in our programming specially when we are using php .
time() and date() these two functions are very important regarding our concern .

see following line of php code :-
$a = time();
time() function returns total number of seconds passed till date from 1st jan 1970 .
date() function is used to get date formatted according to our wish .
function date() can have two parametes:-
1) format of time stamp that we want to show
2) optional:- timestamp which we need to use to get date

first parameter is string that shows that exact output format  . some characters are usefull like
Y -- to show current year
m -- to show current month number
d -- to show today's dat
H -- current hour   24 hour format
i -- to show current minute
s -- to get current seconds
t -- shows number of days in current month  or last date of current month


following are some uses date() function :-

echo  date(""); // this will print nothing
echo date("Y-m-d H:i:s"); // this will show complete time stamp i.e.  2013-10-16 12:00:00 as your system time

echo date("Y-9-d 12:00:s"); // this will show  2013-9-16 12:00:45

these were examples of formatting of time stamp that we want to show ;

second parameter is time stamp itself .
for example :-

 echo date("Y-m-d H:i:s" , time());  // this will show  current time
  echo date("Y-m-d H:i:s" , time() + 500);  // this will show  time after 500 seconds

  echo date("Y-m-d H:i:s" , time() + 86400 );  // this will show tomorrow's time because 86400 is number of seconds in one day .

if we want to see time 5 days ahead  then we need to do is
  echo date("Y-m-d H:i:s" , time()  + 5*86400);

similarly if we want to see time 5 days back then we need to do is
  echo date("Y-m-d H:i:s" , time()  - 5*86400);


if we need to find how many days are in this month or any month then we use "t" in format string (first parameter) .
like

$number_of days_this month = date("t"); // it will give only last date of the month

Thanks and please ask in comment if you need any clearification .

No comments:

Post a Comment