1

I have a strange problem with a JSON response where I am retrieving 3 dates. Two are relating to a subscription start and end date from one table, and another date is the members date of birth.

In the JSON output, these three dates are retrieved. However, the date of birth and the end subscription date are displayed as objects, while the start subscription date is returned as a string. All 3 dates come from fields in the database that are set to DATE and not DATETIME or equivalent.

So my JSON output is:

{
    "dob": {
        "date": "1999-09-28 00:00:00",
        "timezone_type": 3,
        "timezone": "Europe/London"
    },
    "msuStart": "2014-04-17",
    "msuEnd": {
        "date": "2014-04-30 00:00:00",
        "timezone_type": 3,
        "timezone": "Europe/London"
    }
}

What I need to do is get the date of birth and subscription end date to be formatted in the same way as the start subscription date. So I want the dates to be output like 2014-05-01 instead of 2014-05-01 00:00:00. It's confusing me as to why only one date is being output correctly while the other two aren't.

The JQuery code is here:

    var searchCentres = $('#centreSearchForm');
    searchCentres.submit(function () {

        $('.memberContainer').show();

        $.ajax({
            type: searchCentres.attr('method'),
            url: searchCentres.attr('action'),
            data: searchCentres.serialize(),
            success: function (data) {
                var CentreName = (data.centreName);
                var ActiveMembers = (data.actMem);
                var ExpiringMembers = (data.expMem);
                var NewMembers = (data.newMem);
                var RenewalMembers = (data.renMem);
                var ActiveMemberList = (data.actMemList)

                $('.searchedCentre').text(CentreName);
                $('.centreActive').text(ActiveMembers);
                $('.centreExpiring').text(ExpiringMembers);
                $('.centreSuccess').text(NewMembers);
                $('.centreRenewing').text(RenewalMembers);

                $('#searchedCentreMembers > tbody:last').empty();

                $.each(ActiveMemberList, function(i, item) {

                    alert(ActiveMemberList[i].dob.date);

                    $('#searchedCentreMembers > tbody:last').append('<tr><td>' + ActiveMemberList[i].id + '</td><td>' + ActiveMemberList[i].firstName + ' ' + ActiveMemberList[i].surname + '</td><td>' + age + '</td><td>' + ActiveMemberList[i].msuStart + '</td><td>' + ActiveMemberList[i].msuEnd + '</td></tr>');
                });
            }
        });

        return false;
    });

My PHP code (which uses Symfony) is here:

    $activeMemberList = $dm->createQuery('
    SELECT mc.id, mc.surname, mc.firstName, mc.gender, mc.dob, max(msu.startDate) AS msuStart, msu.endDate as msuEnd, msu.renewal, COUNT(mc.id) AS counting
    FROM InstructorBundle:MapCentreSubscriptions msu 
    LEFT JOIN InstructorBundle:MapCentreContacts mc WHERE msu.contact = mc.id
    LEFT JOIN InstructorBundle:MapMemberCategories mmc WHERE mc.category = mmc.id
    LEFT JOIN InstructorBundle:MapBranches mb WHERE msu.branchId = mb.id
    WHERE msu.branchId = :searched
    AND msu.startDate BETWEEN :lastyear AND :today
    AND msu.noLongerSubscribing = :nls
    AND mb.entryType = :centre'
    )->setParameters(array(
                'today' => $dateToday,
                'lastyear' => $date1Year,
                'nls' => '0',
                'centre' => 'Centre',
                'searched' => $centreID
    ));

    $actMemList = $activeMemberList->getResult();

    $response = array(
                    "centreName" => $centre,
                    "actMem" => $actMem, 
                    "expMem" => $expMem,
                    "newMem" => $newMem,
                    "renMem" => $renMem,
                    "actMemList" => $actMemList
                );

    return new JsonResponse($response);
1
  • Please post the code which is generating the JSON. Personally, I'd make all the dates be returned as objects as that will give you more flexibility on the client side. May 1, 2014 at 9:12

2 Answers 2

0

You need to access the date string, split it at " " and select the 0th item.

  • You can access the date like this:

alert(output.dob.date);

After that you just need to split it at " " and select the 0th item.

alert(output.dob.date.split(" ")[0]);

VIEW DEMO

var output = {
    "dob": {
        "date": "1999-09-28 00:00:00",
        "timezone_type": 3,
        "timezone": "Europe/London"
    },
    "msuStart": "2014-04-17",
    "msuEnd": {
        "date": "2014-04-30 00:00:00",
        "timezone_type": 3,
        "timezone": "Europe/London"
    }
};

alert(output.dob.date.split(" ")[0]);
3
  • I am aware of splitting the date, I'm wondering why 2 out of the 3 dates are being returned as objects when all 3 dates are stored the same and in the same format on the database? May 1, 2014 at 9:24
  • 1
    I am pretty sure they are of different format in the database. Could you provide a screenshot?
    – martynas
    May 1, 2014 at 9:24
  • Well I'm 100% sure they are not. All fields are set to DATE, all data within those fields are formatted like 2014-05-01. There are no times stored on the database. May 1, 2014 at 9:25
0
"msuEnd": {
        "date": "2014-04-30 00:00:00",
        "timezone_type": 3,
        "timezone": "Europe/London"
    }

Is a correct representation of DateTime object in JSON.

If you want to represent your field as a string with special format, then the best way to do this is to implement a custom field type, e.g. my_date

<?php
# src/My/Bundle/Type/MyDate.php
namespace My\Bundle\Type;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\VarDateTimeType;
use Doctrine\DBAL\Types\Type;

class MyDate extends VarDateTimeType
{
    public function getName() {
        return 'my_date';
    }

    public function convertToPHPValue($value, AbstractPlatform $platform) {
        $date = parent::convertToPHPValue($value, $platform);
        if ($date instanceof \DateTime)
            return $date->format('Y-m-d');
        return $date;
    }
}

Then register it

# app/config/config.yml
doctrine:
    dbal:
        types:
          my_date: My\Bundle\Type\MyDate

And use it for your entity

/**
 * @ORM\Column(type="my_date", name="startDate", nullable=true)
 */
protected $startDate;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.