简明现代魔法 -> PHP服务器脚本 -> 关于PHP的Date()函数
关于PHP的Date()函数
2009-09-15
PHP date()函数的作用是给日期和时间定义一个“timestamp”。timestamp字面上翻译是时间邮票,但是专业翻译叫时间戳。
Timestamp:从1970年1月1日起格林尼治标准时间(GMT)规定了一秒钟的标准当量,timestamp就是指以这个为标准的总的秒数。这类似于Unix Timestamp。
date()函数的语法
//语法 date(format,timestamp); //参数 format——Required. Specifies the format of the timestamp 必要参数。指定timestamp的格式(format of the timestamp) timestamp——Optional. Specifies a timestamp. Default is the current date and time (as a timestamp) 可选参数。指定一个timestamp。默认值是当前日期和时间(以此作为timestamp)
定义日期
Date()函数中的第一个参数定义了日期/时间的格式。它是用字母来表示日期/时间的格式。
下面对这些字母作具体说明:
d - The day of the month (01-31)
d – 每月包含的天数(01-31)
m - The current month, as a number (01-12)
m – 当前月份,用数字(01-12)表示
Y - The current year in four digits
Y – 当前的年份,用四位数字表示
其他字符,如:"/" "." "-" 也可以插入上述的日期/时间格式字母之间来定义显示格式,具体如下:
<?php
echo date("Y/m/d");
echo "
";
echo date("Y.m.d");
echo "
";
echo date("Y-m-d");
?>
程序输出为:
2012/05/21
2012.05.21
2012-05-21
TimeStamp的使用
Date()函数中的第二个参数指定了一个timestamp。这个参数是一个可选(optional)参数。如果你不指定这个参数,那么将默认使用当前时间。
在下面的例子中,我们将使用mktime()函数为明天创建一个timestamp。
Mktime()函数为指定的日期返回了Unix timestamp。
语法:mktime(hour,minute,second,month,day,year,is_dst)
我们通过给mktime()中的day自变量(argument)加入一个timestamp直接前进到将来的某一天,具体如下:
<?php
$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));
echo "Tomorrow is ".date("Y-m-d", $tomorrow);
?>
上述代码将输出下面的结果:
Tomorrow is 2012-05-22
给数据库记录添加实时时间字段
调用date()函数给变量$date赋值,然后就可以将它插入到数据库中。在有些场合下,需要查询记录是什么时候插入到数据库中的,这个方法可以满足这个需求。
$date = date("Y-m-d");
$strSql="insert into map(service,register_date)
values('$service','$date')";
$result=mysql_query($strSql,$myconn) or die(mysql_error());

