简体   繁体   中英

How to pass Javascript date object (formatted datetime) from Laravel API

My Laravel 5 API pulls regular datetime columns from my MySQL db. My JSON datetime output looks like this:

2015-08-13 13:45:00

but the widget reading my JSON expects a JavaScript Date Object? What would be the syntax to pass my datetime as a JavaScript Date Object?

My current Laravel method looks like so:

public function transform($events)
{
    return [
        'startdt' => $events['event_start'],
        'enddt'   => $events['event_end'],
    ];
}

Here's the (partial) JSON produced:

{
    "events": 
[
{
    "startdt": "2015-07-15T20:49:00+00:00",
    "enddt": "2015-07-15T20:49:00+00:00"
},
{
    "startdt": "2015-07-15T20:53:00+00:00",
    "enddt": "2015-07-15T20:53:00+00:00"
},

This is the code I have in my widget JS file:

'use strict';

angular
  .module('demo', ['mwl.calendar', 'ui.bootstrap', 'ngTouch', 'ngAnimate'])
  .controller('MainCtrl', function ($modal, moment, $http) {

var vm = this;
vm.calendarView = 'month';
vm.calendarDay = new Date();

$http.get('http://1.1.1.1/project/public/api/events').success(function(events) {    
    vm.events = events.events;
}); 

What would be the syntax to parse the datetime into Javascript Data Object?

This code will loop through your array and convert the date strings to date objects.

$http.get('http://1.1.1.1/project/public/api/events').success(function(events) {
    for (var i = 0; i < events.events.length; i++) {
        events.events[i].startdt = new Date(events.events[i].startdt);
        events.events[i].enddt = new Date(events.events[i].enddt);
    }
    vm.events = events.events;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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