【问题标题】:A non well formed numeric value encountered when converting DateTime转换 DateTime 时遇到格式不正确的数值
【发布时间】:2015-11-03 21:05:03
【问题描述】:

我在 Angular 中使用 fullCalendar 插件/指令,目前在尝试将日期/时间保存到我的数据库时遇到问题。

这些是发布到我的服务器的值:

{"title":"Hey","start":"2015-08-13T00:00:00.000Z","end":"2015-08-13T00:00:00.000Z","allDay":true}

现在在我的控制器中,我尝试将日期/时间字符串都转换为有效的日期/时间格式,然后再保存到我的数据库中:

public function store(ScheduleRequest $request)
{
    $schedule = new Schedules;
    $schedule->allDay = $request->allDay;
    $schedule->start = strtotime(date('Y-m-d H:i:s', $request->start));
    $schedule->end = strtotime(date('Y-m-d H:i:s', $request->end));
    $schedule->title = $request->title;

    if ($schedule->save())
    {
        return [
            'success' => 'Data Was Saved Successfully'
        ];
    }
}

这是我得到的错误:

遇到格式不正确的数值

我想知道如何在 PHP 中使用指定的格式将两个日期时间值转换为有效的日期时间对象。

【问题讨论】:

  • 哪行代码抛出了这个错误?
  • 第 42 行,我有 $schedule->start = strtotime(...);
  • 啊,您的日期/时间字符串不正确,请参阅:php.net/manual/en/datetime.formats.php
  • 是的,我知道,我的问题是给出返回给服务器的字符串,如何将其转换为我指定格式的有效日期时间对象。
  • 既然你用的是laravel,为什么不用Carbon,它已经加载到laravel了,这里是文档(github.com/briannesbitt/Carbon

标签: php datetime laravel fullcalendar


【解决方案1】:

编辑:对不起,strtotime 没有按照我的想法做,看起来您希望 DateTime::createFromFormat 从字符串创建 DateTime 对象,然后您可以从那里转到 unix 时间戳。

【讨论】:

  • 您好,感谢您的回复,但我在执行此操作时仍然遇到同样的错误。
【解决方案2】:

strtotime 将字符串转换为时间戳,而 date 将时间戳转换为字符串,您需要使用 strtotime 反转日期,如下所示:

public function store(ScheduleRequest $request)
{
    $schedule = new Schedules;
    $schedule->allDay = $request->allDay;
    $schedule->start = date('Y-m-d H:i:s', strtotime($request->start));
    $schedule->end = date('Y-m-d H:i:s', strtotime($request->end));
    $schedule->title = $request->title;

    if ($schedule->save())
    {
        return [
            'success' => 'Data Was Saved Successfully'
        ];
    }
}

【讨论】:

  • 非常感谢,这正是我做错的,现在可以了。 :D
【解决方案3】:

添加 strtotime($mydateValue) 为我修复了它。

【讨论】:

    猜你喜欢
    • 2014-09-18
    • 1970-01-01
    • 2015-10-08
    相关资源
    最近更新 更多