简体   繁体   English

PHP Carbon每月第n天

[英]PHP Carbon nth days of the month

January 19, 2018 is the third Friday of the month. 2018年1月19日是该月的第三个星期五。

I want the number 3 denoting that this is the third Friday. 我想要数字3表示这是第三个星期五。 Can Carbon do this? Carbon可以这样做吗?

Further, I'll then be using that to check to see if another date is before or after the third Friday of another month. 此外,我将使用它来检查另一个日期是否在另一个月的第三个星期五之前或之后。 For instance, is February 17, 2018 before or after the third Friday in February? 例如,2018年2月17日在2月的第三个星期五之前还是之后?

Carbon is a layer on top of the PHP class DateTime , which is very powerful as it supports many formats that are outlined here , specifically you're looking for the Relative Formats . Carbon是PHP类DateTime之上的一层,它具有非常强大的功能,因为它支持此处概述的许多格式,特别是您在寻找相对格式

Third friday of february is a valid Relative Format, therefore, you can do something like this: Third friday of february是有效的相对格式,因此,您可以执行以下操作:

Carbon::parse('February 17th') > Carbon::parse('third friday of february');

And that will produce true , whereas: 这将产生true ,而:

Carbon::parse('February 15th') > Carbon::parse('third friday of february');

Will produce false . 会产生false

You need to be mindful that formatting is very important when constructing this way, for example, third friday in february is not valid. 您需要谨记,以这种方式构造格式时非常重要,例如, third friday in february是无效的。


I don't believe that there's any functionality within the DateTime class that would allow for the first part in a single DateTime format, however, you can use something like this: 我不相信DateTime类中有任何功能可以允许第一部分采用单一的DateTime格式,但是,您可以使用如下所示的内容:

  1. Determine the day of the provided date 确定提供日期的日期
  2. Find the first of that day in the month 查找该月的第一天
  3. Compare (number of days / 7) between your date and the first day 比较您的日期和第一天(天数/ 7)

eg: 例如:

$date = Carbon\Carbon::parse('January 18 2018');

$firstDay = Carbon\Carbon::parse("first {$date->format('l')} of {$date->format('F')}");
$nth = $firstDay->diffInDays($date) / 7 + 1;

echo "{$date->format('Y-m-d')} is the #{$nth} {$date->format('l')} in this month";

Apparently it can. 显然可以。

Edit: Ignore this 编辑:忽略此

I don't think Carbon can do exactly what you're asking directly, but doing some calculations using the builtin getters I'm sure you could achieve this quiet easily. 我不认为Carbon可以完全满足您的直接要求,但是使用内置的吸气剂进行一些计算,我相信您可以轻松实现这种安静。

http://carbon.nesbot.com/docs/#api-getters http://carbon.nesbot.com/docs/#api-getters

Start with parsing the date: 首先解析日期:

$dt = Carbon::parse('2018-19-1 23:26:11.123789');

Then use weekOfMonth , dayOfMonth , dayOfWeek , etc. 然后使用weekOfMonthdayOfMonthdayOfWeek等。

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

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