php开发笔记系列(三)-日期与时间
? 前两篇完成了《php开发笔记系列(一)-pdo使用》和《php开发笔记系列(二)-字符串使用》,今天开始研究一下php中的日期时间处理和mysql中的日期时间处理,《php开发笔记系列(三)-日期与时间》。
?
? 日期时间是平常用得比较多的函数,在java中我们通过new date()可以获取服务器的当前时间,通过simpledateformat类,并指定formatstring,可以将date对象的值格式化成指定的形式。同理,在php中,同样有类似的类和函数,那就是time函数和date函数。time()类似于new date(),能够获取服务器当前时间,date函数类似于simpledateformat类。
1. 使用time函数获取服务器当前时间,使用date函数进行格式化
file:time.phpurl:http://localhost:88/datetime/timephp
?
2. 通过字符串构造日期时间
file:strtotime.phpurl:http://localhost:88/datetime/strtotime.php
?3. 基于当前时间的日期时间计算
file:date-compute.phpurl:http://localhost:88/datetime/date-compute.php
?
4. 在sql中处理日期时间
select now()select current_timestamp();select date_format(now(), %y-%m-%d);select date_format(now(), %h:%i:%s);select date_format(now(), %w %w %p);
?
5. 在sql中进行日期计算
? 使用date_add函数进行未来日期的计算
select date_add(now(), interval 1 year);select date_add(now(), interval 1 month);select date_add(now(), interval 1 day);select date_add(now(), interval 1 hour);select date_add(now(), interval 1 minute);select date_add(now(), interval 1 second);
?
? 使用date_sub函数进行过去日期的计算
select date_sub(now(), interval 1 year);select date_sub(now(), interval 1 month);select date_sub(now(), interval 1 day);select date_sub(now(), interval 1 hour);select date_sub(now(), interval 1 minute);select date_sub(now(), interval 1 second);
?
? 上述函数的执行结合也可用于sql语句当中,如查询前三天的日志信息,sql如下:
select * from log where create_time between select date_sub(now(), interval 3 day) and select date_add(now(), interval 1 day);
?
? 本文地址:http://ryan-d.iteye.com/blog/1543363
?