PHP:获取第一个月前 6 个月日期的最简单方法?

发布于 2024-08-28 18:55:58 字数 90 浏览 3 评论 0原文

如果今天是 2010 年 4 月 12 日 它应该返回 2009 年 10 月 1 日

我用谷歌搜索过的一些可能的解决方案似乎过于复杂,有什么建议吗?

So if today was April 12, 2010
it should return October 1, 2009

Some possible solutions I've googled seem overly complex, any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

月棠 2024-09-04 18:55:59

嗯,也许是这样的;

echo date("F 1, Y", strtotime("-6 months"));

编辑;

如果您想指定自定义日期使用;

echo date("F, 1 Y", strtotime("-6 months", strtotime("Feb 2, 2010")));

Hm, maybe something like this;

echo date("F 1, Y", strtotime("-6 months"));

EDIT;

if you would like to specify a custom date use;

echo date("F, 1 Y", strtotime("-6 months", strtotime("Feb 2, 2010")));
傾城如夢未必闌珊 2024-09-04 18:55:59

有点黑客但有效:

<?php

$date = new DateTime("-6 months");
$date->modify("-" . ($date->format('j')-1) . " days");
echo $date->format('j, F Y');

?>

A bit hackish but works:

<?php

$date = new DateTime("-6 months");
$date->modify("-" . ($date->format('j')-1) . " days");
echo $date->format('j, F Y');

?>
失退 2024-09-04 18:55:59

使用 mktimedate

$date_half_a_year_ago = mktime(0, 0, 0, date('n')-6, 1, date('y'))

要使新日期相对于给定日期而不是今天,请使用第二个参数调用 date

$given_timestamp = getSomeDate();
$date_half_a_year_ago = mktime(0, 0, 0, date('n', $given_timestamp)-6, 1, date('y', $given_timestamp))

格式化输出,只需再次使用 date 即可:

echo date('F j, Y', $date_half_a_year_ago);

use a combination of mktime and date:

$date_half_a_year_ago = mktime(0, 0, 0, date('n')-6, 1, date('y'))

to make the new date relative to a given date and not today, call date with a second parameter

$given_timestamp = getSomeDate();
$date_half_a_year_ago = mktime(0, 0, 0, date('n', $given_timestamp)-6, 1, date('y', $given_timestamp))

to output it formatted, simply use date again:

echo date('F j, Y', $date_half_a_year_ago);
风柔一江水 2024-09-04 18:55:59

它在评论中进行了讨论,但接受的答案有一些不需要的 strtotime() 调用。可以简化为:

date("F 1, Y", strtotime("Feb 2, 2010 - 6 months"));

另外,您可以像这样使用 DateTime() ,我认为这同样具有可读性:

(new DateTime('Feb 2, 2010'))->modify('-6 months')->format('M 1, Y');

或者使用静态方法....

DateTime::createFromFormat('M j, Y','Feb 2, 2010')
    ->modify('-6 months')
    ->format('M 1, Y');

It was discussed in comments but the accepted answer has some unneeded strtotime() calls. Can be simplified to:

date("F 1, Y", strtotime("Feb 2, 2010 - 6 months"));

Also, you can use DateTime() like this which I think is equally as readable:

(new DateTime('Feb 2, 2010'))->modify('-6 months')->format('M 1, Y');

Or using static method....

DateTime::createFromFormat('M j, Y','Feb 2, 2010')
    ->modify('-6 months')
    ->format('M 1, Y');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文