Date and Time in PHP

How can I get current data and time in php?
My time is 7 hr faster then server time. How can I manipulate it?
Using php date and time?

Explanation

Date and Time using php?
The following portion has the code that can be used in php to get date and time
Knowing current date:

Example:
$dat = date('r');
echo($dat);
?>


code:

<?php
$dat = date('r');
echo($dat);
?>


Here we use the date() funxtion of php which returns a string in specified format.
'r' states for unix format of date.
With date() function we can specify any format of date
Exmaple:

$dat = date('M-d-Y');
echo($dat);
?>


code:

<?php
$dat = date('M-d-Y');
echo($dat);
?>


Here 'M' states for Month, 'd' for day, 'Y' for year.
Knowing past / future date based on time:
Getting the date of a nearest time. Say date of the time less than 5 hours of the current server time.

Example:
$date = date('r',time()-(3600*5));
echo "Date of time less than 5 hrs - $date";
?>


code:

<?php
$date = date('r',time()-(3600*5));
echo "Date of time less then 5 hrs - $date";
?>


Here we use the time() and date() functions of php.
time() gives current time in milliseconds.
To get a date less then 5hrs, we reduce the time value by 5 hrs (i.e 5*3600 milliseconds).
We pass the format and milliseconds as argument to create the date for that time.
Getting Day/Date details of future dates
Day info of 13-5-2005
Example:


$mkt = mktime(0,0,0,5,13,2005);
$ds = date('r',$mkt);
echo("
".$ds);

$ds = date('M-D-Y',$mkt);
echo("
".$ds);
?>


For getting the values we use the function mktime() and date().
mktime() is used to create the long value for the date we wanted info for.
We pass argument for mktime as mktime(hour,min,sec,month,date,year)
The returned value of mktime is passed to date and required format of date was retrieved.
Code:

<?php
$mkt = mktime(0,0,0,5,13,2005);
$ds = date('r',$mkt);
echo($ds);
$ds = date('M-D-Y',$mkt);
echo($ds);
?>




Getting current time
By using the following code, we can get current time.
We use localtime() function of php. It returns an array.
From the array we get the datas.
Example:

$tim = localtime(time(),true);
echo($tim['tm_hour'].":".$tim['tm_min'].":".$tim['tm_sec']);
?>


Code:

<?php
$tim = localtime(time(),true);
echo($tim['tm_hour'].":".$tim['tm_min'].":".$tim['tm_sec']);
?>

PHP Topics


Ask Questions

Ask Question