How to handle datetime between php (Laravel api) and javascript (AngularJS)

◇◆丶佛笑我妖孽 提交于 2021-02-05 18:52:26

问题


I'm utterly stuck trying to make php api exchange dates with angular frontend.

From PHP to JS I seem to have it sorted. Since Laravel handles dates through Carbon I just added \Carbon\Carbon::setToStringFormat('c'); to app.php which makes dates come out in ISO 8601.

PHP example:

2015-02-04T00:53:51+02:00

AngularJS date filter also seems to understand this format well and even reads the timezone correctly.

What I have yet to get working is posting JS date objects back to PHP api.

JS example:

2015-02-05T13:00:00.000Z

Javascript date format ends up with milliseconds added to the string and in default configuration Carbon complains about trailing data.

Also browsers seem to automatically translate my dates into UTC time.

Manually using new Carbon('jsDateString') seems to work at first but on closer inspection timezone data is not considered.

So my question is what would be the best and most automatic solution to send dates back to Laravel php api from AngularJS frontend?


回答1:


$dt = Carbon::now();
echo $dt->toW3cString();       // 2015-02-05T14:50:55+01:00

since carbon can print it it can also parse this format

Carbon::parse('2015-02-05T14:50:55+01:00');

in javascript with moment.js momentjs.com

moment().format(); // 2015-02-05T14:50:55+01:00



回答2:


1) make a Carbon date in Laravel controller

$date_from = Carbon::now();
return view('reports', compact('date_from'));

2) You need to init Date in Angular conctoller

rrApp.controller('reportsCtrl', ['$scope', '$filter', function($scope, $filter)
{
        $scope.start_date = new Date("{{$date_from}}");
        $scope.start_date = new Date($filter("date")($scope.start_date, 'yyyy-MM-dd'));// only date, no time

}]); 

3) use it

<input type="date" class="form-control" ng-model="start_date">

4) Do NOT try to init the variable in ng-init, it would not work:



来源:https://stackoverflow.com/questions/28344550/how-to-handle-datetime-between-php-laravel-api-and-javascript-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!