Tuesday, February 22, 2022

[FIXED] How to remove time information from date in this json structure?

Issue

I am using cakephp v3.

I have a simple Model function;

public function getXXXoutput($xxx_term, $start_date, $end_date)    
{           
    $monthly_XXX_curves = TableRegistry::get('MonthlyXXXCurves');        
    $query = $monthly_XXX_curves
            ->find()                        
            ->select( ['date_transacted', 'output'] ) 
            ->toArray();

    return $query;        
}

The controller function looks like this;

public function apiGetXXX()
{
    $json_output = $this->MonthlyXXXCurves->getXXXoutput($xxx_term, $start_date, $end_date);
    echo json_encode($json_output);
}

The json format the controller returns looks like this;

[
{
output: 1.37,
date_transacted: "2015-01-01T00:00:00+0000"
},
{
output: 1.62,
date_transacted: "2015-02-01T00:00:00+0000"
}
]

I would like to remove the time information from date_transacted such that the final json structure would look like this;

[
{
output: 1.37,
date_transacted: "2015-01-01"
},
{
output: 1.62,
date_transacted: "2015-02-01"
}
]

How to modify the controller function to achieve the desired json structure?


Solution

Select date_transacted and format as DATE in your query

public function getXXXoutput($xxx_term, $start_date, $end_date)    
{           
    $monthly_XXX_curves = TableRegistry::get('MonthlyXXXCurves');        
    $query = $monthly_XXX_curves
            ->find()                        
            ->select(['transacted' => 'DATE(date_transacted)', 'output']) 
            ->toArray();

    return $query;        
}


Answered By - Salines

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.