简体   繁体   English

获得上个月的第一天和最后一天的最佳方式?

[英]The best way to get the first and last day of last month?

I'm looking for the best way to get the first and the last day of a last month.我正在寻找获得上个月第一天和最后一天的最佳方式。 I use them for make SQL queries to get stats of last month.我使用它们进行 SQL 查询以获取上个月的统计信息。

I think that this is the best way, more optimized but not more comprensive, anyone have another way to do the same?我认为这是最好的方法,更优化但不是更全面,有人有另一种方法吗?

    $month_ini = date("Y-m-d", mktime(0, 0, 0, date("m", strtotime("-1 month")), 1, date("Y", strtotime("-1 month"))));

    $month_end = date("Y-m-d", mktime(0, 0, 0, date("m", strtotime("-1 month")), date("t", strtotime("-1 month")), date("Y", strtotime("-1 month"))));

Thanks!!谢谢!!

In PHP 5.3, you can use the DateTime class : 在PHP 5.3中,您可以使用DateTime类:

<?php

$month_ini = new DateTime("first day of last month");
$month_end = new DateTime("last day of last month");

echo $month_ini->format('Y-m-d'); // 2012-02-01
echo $month_end->format('Y-m-d'); // 2012-02-29

Last day of the previous month: 上个月的最后一天:

date("Y-m-d", mktime(0, 0, 0, date("m"), 0));

First day of the previous month: 上个月的第一天:

date("Y-m-d", mktime(0, 0, 0, date("m")-1, 1));

I use these in MySQL and PHP scripts, short and simple: 我在MySQL和PHP脚本中使用这些,简短而简单:

echo date('Y-m-d', strtotime('first day of last month'));
echo date('Y-m-d', strtotime('last day of last month'));

MySQL use example: MySQL使用示例:

$query = $db->query("SELECT * FROM mytable WHERE 1 AND mydate >= '".date('Y-m-d', strtotime('first day of last month'))."'");

If you're doing this for the purpose of a MySQL query, have you considered using the MONTH function , eg 如果你是为了MySQL查询而这样做的,你是否考虑过使用MONTH函数 ,例如

SELECT [whatever stats you're after] FROM table
WHERE MONTH(date_field) = 12 and YEAR(date_field) = 2011

This would get your stats for December. 这将获得12月的统计数据。 If you start to experience performance problems and the historical data doesn't change, you might want to denormalise the data into an aggregate table (rolled up by the smallest increment you need, eg daily/hourly/monthly etc). 如果您开始遇到性能问题且历史数据没有变化,您可能希望将数据非规范化为聚合表(按您需要的最小增量汇总,例如每日/每小时/每月等)。

you can do this in MySQL: 你可以在MySQL中做到这一点:

WHERE `DateAndTime` >= '2012-02-01 00:00:00'
AND `DateAndTime` < '2012-03-01 00:00:00'

let mysql deal with dates. 让mysql处理日期。

anything that is for the database to do, let it do. 任何数据库要做的事情,让它做。

like this: 像这样:

mysql_query("set @last_day=last_day(now()-interval 1 month),@first_day=(@last_day-interval 1 month)+interval 1 day");
$result=mysql_query("select * from `table` where (`date` between @first_day and @last_day)");

the best is that this will work even if the year changes. 最好的是,即使年份发生变化,这也会奏效。

just remember to change the database timezone to match php. 只记得更改数据库时区以匹配php。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM