php POST数据到datetime

时间:2016-01-15 05:14:47

标签: php datetime closures

我的项目存在问题。我想创建一个.ics文件,其中包含由网站用户定义的开始和结束时间。所以我得到了开始和结束年份以及开始/结束时间的字符串。现在我想从这些数据中创建一个DateTime对象。我的问题是我现在只是从时间戳中得到时间戳而不是来自字符串:

$eventStartDay    = $_POST["eventStartDay"];
$eventStartMonth  = $_POST["eventStartMonth"];
$eventStartYear   = $_POST["eventStartYear"];
$eventStartHour   = $_POST["eventStartHour"];
$eventStartMinute = $_POST["eventStartMinute"];
$eventStartSecond = $_POST["eventStartSecond"];
$startDateTime    = $eventStartYear . "-" . $eventStartMonth . "-" 
                  . $eventStartDay . "T" . $eventStartHour . ":" 
                  . $eventStartMinute . ":" . $eventStartSecond . "+01:00";

$eventEndDay    = $_POST["eventEndDay"];
$eventEndMonth  = $_POST["eventEndMonth"];
$eventEndYear   = $_POST["eventEndYear"];
$eventEndHour   = $_POST["eventEndHour"];
$eventEndMinute = $_POST["eventEndMinute"];
$eventEndSecond = $_POST["eventStartSecond"];
$endDateTime    = $eventEndYear . "-" . $eventEndMonth . "-" 
                . $eventEndDay . "T" . $eventEndHour . ":" 
                . $eventEndMinute . ":" . $eventEndSecond . "+01:00";

$cal = new SimpleICS();
$cal->addEvent(function($e) {
  $e->startDate = new DateTime($startDateTime);
  $e->endDate   = new DateTime($endDateTime);

我用var_dump()检查了字符串,得到了正确的答案。他们应该是这样的:' 2016-01-18T19:00:00 + 01:00'

1 个答案:

答案 0 :(得分:0)

引用PHP manual on Anonymous functions

  

闭包还可以从父作用域继承变量。必须将任何此类变量传递给use语言构造。

所以你需要关闭DateTime对象,例如你需要做什么

$cal->addEvent(function($e) use ($startDateTime, $endDateTime) {
  $e->startDate = new DateTime($startDateTime);
  $e->endDate   = new DateTime($endDateTime);
}