strtotime用法

eex2 9年前

习惯使用Unix时间戳来保存日期和时间了,渐渐觉得strtotime方法实在很好用。通常的用法是把客户端的日期和时间字符串通过 strtotime 转换成时间戳后保存在数据库中,然后在显示的时候使用date格式化成需要的格式显示,比较灵活。其实,strtotime还有很多用法,甚至有一点人工智能的作用呢,呵呵~

因为strtotime可以解析任何英文的日期时间表达式,例如

   1. strtotime("+1 day");// 1天后

   2. strtotime("today");// 今天

   3. strtotime("+1 hours");// 1小时后

   4. strtotime("-1 day");// 昨天

通过这样的表达式我们可以方便地进行日期比较,这比使用Mysql的方法或者使用其他的Date类要快捷不少。例如:

   1. // 搜索当天创建的记录

   2. 'Select * from `table` where buildTime>'.strtotime("today");

   3. // 搜索一周内创建的记录

   4. 'Select * from `table` where buildTime>'.strtotime("last week");

   5. // 搜索本周创建的记录

   6. 'Select * from `table` where buildTime>'.strtotime("last Monday");