如何使用PHP查找一个月中的第一个和最后一个日期? [英] How can I find the first and last date in a month using PHP?

查看:29
本文介绍了如何使用PHP查找一个月中的第一个和最后一个日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 PHP 查找一个月中的第一个和最后一个日期?例如,今天是 2010 年 4 月 21 日;我想找到 2010 年 4 月 1 日和 2010 年 4 月 30 日.

How can I find the first and last date in a month using PHP? For example, today is April 21, 2010; I want to find April 1, 2010 and April 30, 2010.

推荐答案

最简单的方法是使用 date,它允许您将硬编码值与从时间戳中提取的值混合在一起.如果您不提供时间戳,则假定为当前日期和时间.

The easiest way is to use date, which lets you mix hard-coded values with ones extracted from a timestamp. If you don't give a timestamp, it assumes the current date and time.

// 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',并用其时间戳中的值替换它们.所以我们可以使用这些符号从时间戳中提取我们想要的值和格式.在上面的例子中:

date() searches the string it's given, like 'm-t-Y', for specific symbols, and it replaces them with values from its timestamp. So we can use those symbols to extract the values and formatting that we want from the timestamp. In the examples above:

  • Y 为您提供时间戳 ('2010') 中的 4 位年份
  • m 为您提供时间戳中的数字月份,前导零 ('04')
  • t 为您提供时间戳的月份 ('30') 中的天数
  • Y gives you the 4-digit year from the timestamp ('2010')
  • m gives you the numeric month from the timestamp, with a leading zero ('04')
  • t gives you the number of days in the timestamp's month ('30')

您可以发挥创意.例如,要获取一个月的第一秒和最后一秒:

You can be creative with this. For example, to get the first and last second of a month:

$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 其他符号和更多详细信息.

See http://php.net/manual/en/function.date.php for other symbols and more details.

这篇关于如何使用PHP查找一个月中的第一个和最后一个日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆