Date and Time

The PHP date() function is used to format date and/or a time and formats as timestamp to a more readable data and time.

date(format, timestamp) //format is required and timestamp is optional

Here are some characters that are commonly uesd for dates:

  • d -- represents the day of the month
  • m -- represents a month
  • Y -- represents a year
  • l -- represents the day of the week

Other characters like '/','.' or '-' can also be inserted between the characters to add additional formatting.

<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>

output:

Today is 2016/02/17
Today is 2016.02.17
Today is 2016-02-17
Today is Wednesday

Use the date() function to automatically update the copyright year on the website

&copy; 2010-<?php echo date("Y"); ?>

Here are some characters that are commonly used for times:

  • h -- 12-hour format of an hour with leading zeros
  • i -- minites with leading zero
  • s -- seconds with leading zeros
  • a -- lowecase ante meridiem and post meridiem

<!DOCTYPE html>
<html>
<body>
<?php
echo "The time is " . date("h:i:sa");
?>
</body>
</html>

output:The time is 11:22:38pm

PHP use date_default_timezone_set() function to set timezone

<?php
date_default_timezone_set("America/New_York");
echo "The time is " . date("h:i:sa");
?>

output:The time is 11:24:21pm

The mktime() function returns the Unix timestamp for a date.The Unix timestamp contais the number of seconds between the Unix Epoch and the time specified.

mktime(hour, minute, second, month, day, year)

<?php
$d=mktime(11, 14, 54, 8, 12, 2014);
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>

output:Created date is 2014-08-12 11:14:54am

The PHP strtotime() function is used to convert a human readable string to a Unix time.

strtotime(time, now)

<?php
$d=strtotime("10:30pm April 15 2014");
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>

output:Created date is 2014-04-15 10:30:00pm

<?php
$d=strtotime("tomorrow");
echo date("Y-m-d h:i:sa", $d) . "<br>";

$d=strtotime("next Saturday");
echo date("Y-m-d h:i:sa", $d) . "<br>";

$d=strtotime("+3 Months");
echo date("Y-m-d h:i:sa", $d) . "<br>";
?>

<?php
$startdate = strtotime("Saturday");
$enddate = strtotime("+6 weeks",$startdate);
while ($startdate < $enddate) {
  echo date("M d", $startdate),"<br>";
  $startdate = strtotime("+1 week", $startdate);
}
?>

<?php
$d1=strtotime("July 04");
$d2=ceil(($d1-time())/60/60/24);
echo "There are " . $d2 ." days until 4th of July.";
?>

上一篇:jQuery的常见操作


下一篇:Java线程池参数