格式化json给出的日期

[英]Format a date given from a json


I search a way to format a date given from a json response. Currently I can pass the date via json response into both format :

我搜索一种格式化json响应给出的日期的方法。目前我可以通过json响应将日期传递给两种格式:

the string format:

字符串格式:

{"date":"2016-11-25T11:24:54+0100"}

or the object format:

或对象格式:

"date":{"timezone":{"name":"Europe\/Paris","location":{"country_code":"FR","latitude":48.86666,"longitude":2.33333,"comments":""}},"offset":3600,"timestamp":1480069808}}

I have to format one of this two json formats into that format: dd/mm/aaaa, example: 25/11/2016

我必须将这两种json格式中的一种格式化为这种格式:dd / mm / aaaa,例如:25/11/2016

This operation must be done in my view, with jQuery/js, or in the controller before send the json reponse:

此操作必须在我的视图中使用jQuery / js完成,或者在发送json响应之前在控制器中完成:

/*            $normalizer = new GetSetMethodNormalizer();      here the code for fomat the date into string
            $callback = function ($dateTime) {
                return $dateTime instanceof \DateTime
                    ? $dateTime->format(\DateTime::ISO8601)
                    : '';
            };
            $normalizer->setCallbacks(array('date' => $callback));*/

            $normalizer->setIgnoredAttributes(array('article'));
            $serializer = new Serializer(array($normalizer), array($encoder));
            $dataJSON = $serializer->serialize($data, 'json');

            $response = new Response();
            $response->setContent($dataJSON);
            $response->headers->set('Content-Type', 'application/json');

            return $response;

2 个解决方案

#1


1  

use PHPs build in DateTime class like

使用PHP构建在DateTime类中

<?php

$date = new Datetime('2016-11-25T11:24:54+0100');
var_dump($date->format('d.m.Y h:i:s')); // string(19) "25.11.2016 11:24:54"

#2


1  

Independently how your controller sends the data, in your view (presentation) you can format it via Moment.js.

独立于您的控制器如何发送数据,在您的视图(演示文稿)中,您可以通过Moment.js格式化它。

For example:

例如:

// Your controller date timestamp
const timestamp = 1480070762;
moment().unix(timestamp).format('DD-MM-YYYY');

I suggest you your controller to act as an API and all views to have flexability to choose the presentation format of the date.

我建议您的控制器充当API,并且所有视图都具有灵活性,可以选择日期的表示格式。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2016/11/25/d310299d4048ca7c41ce8de8411ad72c.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号