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

查看:88
本文介绍了如何使用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()搜索给定的字符串,像'mt-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 给你4位数的年份时间戳('2010')

  • 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天全站免登陆