如何使用 PHP 找到一个月中的第一个和最后一个日期?例如,今天是 2010 年 4 月 21 日;我想查找 2010 年 4 月 1 日和 2010 年 4 月 30 日。
最佳答案
最简单的方法是使用 date
,它可以让您将硬编码值与从时间戳中提取的值混合。如果您不提供时间戳,则假定为当前日期和时间。
// Current timestamp is assumed, so these find first and last day of THIS month
$first_day_this_month = date('m-01-Y'); // hard-coded '01' for first day
$last_day_this_month = date('m-t-Y');
// With timestamp, this gets last day of April 2010
$last_day_april_2010 = date('m-t-Y', strtotime('April 21, 2010'));
date()
在给出的字符串(如 'm-t-Y'
)中搜索特定符号,并将其替换为时间戳中的值。所以我们可以使用这些符号从时间戳中提取我们想要的值和格式。在上面的例子中:
Y
为您提供来自时间戳 ('2010') 的 4 位数年份m
为您提供时间戳中的数字月份,前导零 ('04')t
为您提供时间戳所在月份的天数 ('30')
您可以发挥创意。例如,要获取一个月的第一秒和最后一秒:
$timestamp = strtotime('February 2012');
$first_second = date('m-01-Y 00:00:00', $timestamp);
$last_second = date('m-t-Y 12:59:59', $timestamp); // A leap year!
见 http://php.net/manual/en/function.date.php了解其他符号和更多详细信息。
关于php - 如何使用 PHP 找到一个月中的第一个和最后一个日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2680501/