获取当前时间戳
echo time();
获取当前格式化日期
string date( string format [, int timestamp] )
| 格式化方式 | 说明 | 
|---|---|
| Y | 4位数字年,y为2位数字,如99即1999年 | 
| m | 数字月份,前面有前导0,如01。n 为无前导0数字月份 | 
| F | 月份,完整的文本格式,例如 January 或者 March | 
| M | 三个字母缩写表示的月份,例如 Jan 或者 Mar | 
| d | 月份中的第几天,前面有前导0,如03。j 为无前导0的天数 | 
| w | 星期中的第几天,以数字表示,0表示星期天 | 
| z | 年份中的第几天,范围0-366 | 
| W | 年份中的第几周,如第32周 | 
| H | 24小时格式,有前导0,h为12小时格式 | 
| G | 24小时格式,无前导0,g为对应12小时格式 | 
| i | 分钟格式,有前导0 | 
| s | 秒格式,有前导0 | 
| A | 大写上下午,如AM,a为小写 | 
可选参数 timestamp 表示时间戳,默认为 time() ,即当前时间戳。
我们可以通过 date() 函数提供的丰富格式化来显示需要的时间日期,如下面的例子:
date("Y-m-d",time()); //显示格式如 2008-12-01 
date("Y.m.d",time()); //显示格式如 2008.12.01 
date("M d Y",time()); //显示格式如 Dec 01 2008 
date("Y-m-d H:i",time()); //显示格式如 2008-12-01 12:01
date('Y-m-d');   // 返回当前日期 
时区问题
如果您输出的时间和实际时间差8个小时(假设您采用的北京时区)的话,请检查php.ini文件,做如下设置:
date.timezone = PRC
日期转换为时间戳
strtotime() 函数用于将英文文本字符串表示的日期转换为时间戳,为 date() 的反函数,成功返回时间戳,否则返回 FALSE 。
int strtotime ( string time [, int now] )
参数 time 为被解析的字符串,是根据 GNU 日期输入格式表示的日期。
例子:
echo strtotime("2009-10-21 16:00:10"); //输出 1256112010 
echo strtotime("10 September 2008"); //输出 1220976000 
echo strtotime("+1 day"); //输出明天此时的时间戳
获取指定日期中的所有月份
/** 
* 生成从开始月份到结束月份的月份数组
* @param int $start 开始时间戳
* @param int $end 结束时间戳
*/ 
function monthList($start,$end){
	if(!is_numeric($start)||!is_numeric($end)||($end<=$start)) return '';
	$start=date('Y-m',$start);
	$end=date('Y-m',$end);
	//转为时间戳
	$start=strtotime($start.'-01');
	$end=strtotime($end.'-01');
	$i=0;
	$d=array();
	while($start<=$end){
		//这里累加每个月的的总秒数 计算公式:上一月1号的时间戳秒数减去当前月的时间戳秒数
		$d[$i]=trim(date('Y-m',$start),' ');
		$start+=strtotime('+1 month',$start)-$start;
		$i++;
	} 
	return $d;
}
print_r(monthList(strtotime("2016-08-26"), time()));输出结果:

获取指定日期中的所有日期
function getDatesBetweenTwoDays($startDate, $endDate){
    $dates = [];
    if(strtotime($startDate)>strtotime($endDate)){
        //如果开始日期大于结束日期,直接return 防止下面的循环出现死循环
        return $dates;
    }elseif($startDate == $endDate){
        //开始日期与结束日期是同一天时
        array_push($dates,$startDate);
        return $dates;
    }else{
        array_push($dates,$startDate);
        $currentDate = $startDate;
        do{
            $nextDate = date('Y-m-d', strtotime($currentDate.' +1 days'));
            array_push($dates,$nextDate);
            $currentDate = $nextDate;
        }while($endDate != $currentDate);
        return $dates;
    }
}
print_r(getDatesBetweenTwoDays("2020-02-01", "2020-03-01"));输出结果:
