各种时间操作(PHP)

一、获取时间 1、获取本周一 date('Y-m-d', (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600)); //w为星期几的数字形式,这里0为周日 2、获取本周日 date('Y-m-d', (time() + (7 - (date('w') == 0 ? 7 : date('w'))) * 24 * 3600)); //同样使用w,以现在与周日相关天数算 3、获取上周一 date('Y-m-d', strtotime('-1 monday', time())); //无论今天几号,-1 monday为上一个有效周未 4、获取上周日 date('Y-m-d', strtotime('-1 sunday', time())); //上一个有效周日,同样适用于其它星期 5、获取本月一日 date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00')); //直接以strtotime生成 6、获取本月最后一日 date('Y-m-d', strtotime(date('Y-m', time()) . '-' . date('t', time()) . ' 00:00:00')); //t为当月天数,28至31天 7、获取上月一日 date('Y-m-d', strtotime('-1 month', strtotime(date('Y-m', time()) . '-01 00:00:00'))); //本月一日直接strtotime上减一个月 8、获取上月最后一日 date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00') - 86400); //本月一日减一天即是上月最后一日 9、获取当前时间前6天 date('Y-m-d', strtotime('-6 days')); 10、指定时间加一个月 date("Y-m-d",strtotime("+1 month",strtotime("2012-02-04"))); 11、指定时间加一周 date("Y-m-d",strtotime("+1 week",strtotime("2011-02-04"))); 12、指定时间加一天 date("Y-m-d",strtotime("+1 day",strtotime("2011-02-04"))); 13、当前时间加一天 date('Y-m-d H:i:s',strtotime('+1 day')); 14、当前时间加一小时 date('Y-m-d H:i:s',strtotime('+1 hour')); 15、当前时间加一分钟 date('Y-m-d H:i:s',strtotime('+1 minute')); 16、当前时间加一月 date('Y-m-d H:i:s',strtotime('+1 mouth')); 17、获取当前月的第一天和最后一天 $date = date('Y-m-d'); function getMonth($date){ $firstday = date("Y-m-01",strtotime($date)); $lastday = date("Y-m-d",strtotime("$firstday +1 month -1 day")); return array($firstday,$lastday); } 18、获取上月的第一天和最后一天 $date = date('Y-m-d'); function getlastMonthDays($date){ $timestamp=strtotime($date); $firstday=date('Y-m-01',strtotime(date('Y',$timestamp).'-'.(date('m',$timestamp)-1).'-01')); $lastday=date('Y-m-d',strtotime("$firstday +1 month -1 day")); return array($firstday,$lastday); } 19、获取下月的第一天和最后一天 $date = date('Y-m-d'); function getNextMonthDays($date){ $timestamp=strtotime($date); $arr=getdate($timestamp); if($arr == 12){ $year=$arr +1; $month=$arr -11; $firstday=$year.'-0'.$month.'-01'; $lastday=date('Y-m-d',strtotime("$firstday +1 month -1 day")); }else{ $firstday=date('Y-m-01',strtotime(date('Y',$timestamp).'-'.(date('m',$timestamp)+1).'-01')); $lastday=date('Y-m-d',strtotime("$firstday +1 month -1 day")); } return array($firstday,$lastday); } 二、计算指定时间和当前时间相差年月日时分秒 date_default_timezone_set('PRC');//声明时区 $enddate="2018-6-14 17:29:10"; $date=floor((strtotime($enddate)-strtotime(date('Y-m-d H:i:s')))/86400); echo "相差天数:".$date."天<br/><br/>"; $hour=floor((strtotime($enddate)-strtotime(date('Y-m-d H:i:s')))%86400/3600); echo "相差小时数:".$hour."小时<br/><br/>"; $minute=floor((strtotime($enddate)-strtotime(date('Y-m-d