一日,遇到一个问题,求上一个月的今天。 最开始我们使用 strtotime(”-1 month”) 函数求值,发现有一个问题,月长度不一样的月份的计算结果有误。 比如:2011-03-31,得到的结果是2011-03-03。我们先不追究什么问题,先看如何解决问题。 此时,想起PHP中有一个mktime函数,于是自己写了如下代码:
复制代码 代码如下:
echo date("Y-m-d H:i:s", mktime(date("G", $time), date("i", $time),
date("s", $time), date("n", $time) - 1, date("j", $time), date("Y", $time)));
当执行时,发现结果和strtotime的结果是一样的。
还是基于这个函数,既然无法直接操作月,那么我们从天入手,得到上一个月,然后再使用date拼接数据。如下代码:
复制代码 代码如下:
$time = strtotime("2011-03-31");
/**
* 计算上一个月的今天
* @param type $time
* @return type
*/
function last_month_today($time) {
$last_month_time = mktime(date("G", $time), date("i", $time),
date("s", $time), date("n", $time), - 1, date("Y", $time));
return date(date("Y-m", $last_month_time) . "-d H:i:s", $time);
}
echo last_month_today($time);
但是此时又有了另一个问题,不存在2011-02-31这样的日期,怎么办?现在的需求是对于这样的日期显示当月最后一天。 如下代码:
复制代码 代码如下:
$time = strtotime("2011-03-31");
/**
* 计算上一个月的今天,如果上个月没有今天,则返回上一个月的最后一天
* @param type $time
* @return type
*/
function last_month_today($time){
$last_month_time = mktime(date("G", $time), date("i", $time),
date("s", $time), date("n", $time), 0, date("Y", $time));
$last_month_t = date("t", $last_month_time);
if ($last_month_t return date("Y-m-t H:i:s", $last_month_time);
}
return date(date("Y-m", $last_month_time) . "-d", $time);
}
echo last_month_today($time);
这里需要注意一点: date(”Y-m”, $last_month_time) . “-d”这段代码。在写代码的过程中如果写成了 “Y-” . date(”m”, $last_month_time) . “-d” 则在跨年的时间上有问题。 这点还是在写这篇文章时发现的。
除了这种方法,还可以先算出年月日再拼接字符串,这里就是纯粹的字符串操作了。

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

드림위버 CS6
시각적 웹 개발 도구

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음
