Carbon createFromFormat 意外结果 [英] Carbon createFromFormat unexpected result

查看:69
本文介绍了Carbon createFromFormat 意外结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

::createFromFormat() 导致提前一个月:

::createFromFormat() results in being one month ahead:

var_dump($_GET['archive']);
var_dump(Carbon::createFromFormat('m/Y', $_GET['archive']));

结果:

string '11/2015' (length=7)
object(Carbon\Carbon)[160]
  public 'date' => string '2015-12-01 10:38:41.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/London' (length=13)

推荐答案

看来你倒霉了,因为你在当月 31 号测试.

Seems that you just got unlucky because you were testing on the 31st of the month.

然而,这(显然)是一个记录在案的功能.请参阅:http://php.net/manual/en/datetime.createfromformat.php

However, this is (apparently) a documented feature. See: http://php.net/manual/en/datetime.createfromformat.php

如果您正确"设置格式掩码,它会按您的预期工作.

If you set your format mask "correctly", it works as you'd expect.

$x = Carbon::createFromFormat   ('m/Y', '04/2009');
$y = DateTime::createFromFormat ('m/Y|', '04/2009');
dd ($x, $y);

为了避免歧义,Carbon 函数只是 PHP 底层 DateTime 函数的包装器;我只是想证明这不是让我们头疼的 Carbon 特性.

To avoid ambiguity, the Carbon function is just a wrapper for the underlying DateTime function of PHP; I'm just aiming to prove that this is not a Carbon feature that's causing our headache.

如果您在当月 31 日进行测试,上面的 $x 将被读取为 31 April 2009,将显示为 1st May.

If you test on the 31st of the month, $x above will be read as 31 April 2009 which will be displayed as 1st May.

虽然掩码中有管道符号,但所有未声明的时间变量(His)都设置为零,并且日期变量 (d, m) 设置为 1,因此 $y 将始终如您所愿地响应,无论日期是哪一天一周.

With the pipe symbol in the mask though, all the non-declared time variables (H, i, s) are set to zero, and date variables (d, m) set to 1, so $y will always respond as you expect regardless of the day of the week.

对于我在每月第 4 天晚上 17:46 进行的测试,上面的代码产生以下结果:

For me testing at 17:46 in the evening of the 4th day of the month, the above code produces the following:

Carbon @1233769590 {#219 ▼
    date: 2009-02-04 17:46:30.0 Europe/London (+00:00)
}

DateTime @1233446400 {#217 ▼
    date: 2009-02-01 00:00:00.0 Europe/London (+00:00)
}

在我看来,这是一个非常奇怪的日期/时间函数实现.您希望在现实世界中使用此函数的唯一情况是,您正在从外部源(例如 XML日期"字段)读取数据.

This is a really weird implementation of date/time function in my opinion. The only real-world situation that you'd want to use this function in, is if you're reading data from an external source (such as an XML "date" field).

到底哪个程序员希望他们的程序假设传入数据的缺失时间(或在您的情况下,天)部分应该从运行时执行时间中获取?这绝对是疯狂的疯子.

Which programmer on earth would want their program to assume that the missing time (or in your case, day) component of the incoming data, should be taken from the runtime execution time? It's absolutely crazy bonkers.

这篇关于Carbon createFromFormat 意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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