首页 > 技术文章 > PHP Mysql:时间函数

carolina 2016-06-28 15:28 原文

 

date()----格式化一个本地时间/日期

函数原型:

string date(string $format[, int $timestamp])

返回值:整数timestamp按照字符串 format 生成的字符串

如果没有给出整数timestamp,则使用本地当前时间(默认值time())

format

  • d: 月份中的第几天,有前导零的2位数字  01到31
  • D:星期中的第几天,文本表示,三个字母  Mon到Sun
  • j: 月份中的第几天,没有前导零  1到31
  • l(小写L):星期几,完整的文本格式   Sunday到Saturday
  • N:星期中的第几天   1(星期1 )到7(星期日)
  • S:每月天数后面的英文后缀,2个字符   st,nd,rd或者th.可以和j一起使用
  • w:星期中的第几天,数字表示  0(星期天)到6(星期六)

星期

  • W:年份中的第几周,每周从星期一开始 如:42(当年第42周)

  • F:月份,完整的文本格式,例如 January March    January到December
  • m:数字表示的月份,有前导零    01到12
  • M:三个字母缩写表示的月份   Jan到Dec
  • n:数字表示的月份,没有前导零  1到12
  • t:给定月份所应有的天数  28到31

  • L:是否为闰年  闰年是1,平年为0
  • o:
  • Y:4位数字完整表示的年份  如1999 2003
  • y:2位数字表示的年份  如 99 03

时间

  • a 小写的上午和下午值  am或pm
  • A :大写的上午和下午值  AM或PM
  • B:Swath Internet标准时  000到999
  • g:小时,12小时格式,没有前导零 1到12
  • G:小时,24小时格式,没有前导零 0到23
  • h:小时,12小时格式,有前导零 01到12
  • H:小时,24小时格式,有前导零 00到23
  • i:有前导零的分钟数  00到59
  • s:秒数,有前导零 00到59

MySQL DATETIME格式$today date("Y-m-d H:i:s");// 2001-03-10 17:16:18

time()

原型:

int time(void)

返回从Unix纪元(格林威治时间1970年1月1日00:00:00)到当前时间的秒数

例子:

$nextWeek = time() + (7*24*60*60);

$nextWeek = strtotime('+1 week');

strtotime()

strtotime()将任何英文文本的日期时间解析成整数Unix时间戳

函数原型:

int strtotime(string $time [, int $now = time() ]) 

如提供now参数,时间戳的值相对于now参数给出

如没有提供,now默认等于time();

返回值:

成功则返回时间戳,否则返回false,5.1.0之前返回-1.

参数time取值格式

常用例子

<?php
echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
?>

strtotime失败检查

<?php
$str = 'Not Good';

// previous to PHP 5.1.0 you would compare with -1, instead of false
if (($timestamp = strtotime($str)) === false) {
    echo "The string ($str) is bogus";
} else {
    echo "$str == " . date('l dS of F Y h:i:s A', $timestamp);
}
?>

 详情

推荐阅读