【问题标题】:PHP | Take day of a date, compare it to the current month and transform it into the previous month [duplicate]PHP |取日期,将其与当前月份进行比较并将其转换为上个月[重复]
【发布时间】:2020-12-21 19:45:56
【问题描述】:

如果我的日期等于:2020-04-21

我想取这个日期的日期:21

取当前月份:12 月

按照当时的 12 月来计算:2020-12-21

并将其转换为上个月,保留日期和年份,然后:2020-11-21

我该怎么办?

【问题讨论】:

  • 您可以使用 DateTime 库和 strtotime 函数。它会给你想要的
  • @ÁlvaroGonzález 抱歉,我改了
  • 所以你基本上想设置一个现有日期的月份。其他月份较短时的规则是什么?

标签: php date


【解决方案1】:
<?
$time=strtotime('2020-04-21'); // get unixtime of custom date
$day=date('d', $time); // get day of custom date
$year=date('Y', $time); // get year of custom date
$month=date('m'); // get current month

$time_first=mktime(0, 0, 0, $month, $day, $year); // get unixtime for first
$time_second=strtotime('-1 month', $time_first); // get unixtime previous month

$date_first=date('Y-m-d', $time_first); // string format of first date
$date_second=date('Y-m-d', $time_second); // string format of second date

var_dump($date_first);
var_dump($date_second);
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多