简体   繁体   English

MySQL JSON_OBJECT() 日期时间格式

[英]MySQL JSON_OBJECT() datetime format

I'm creating a JSON structure by using a JSON_OBJECT and JSON_ARRAY functions in my select query.我正在通过在我的选择查询中使用 JSON_OBJECT 和 JSON_ARRAY 函数创建一个 JSON 结构。 The problem I have is with the format in which datetime columns are returned in the formatted JSON result.我遇到的问题是在格式化的 JSON 结果中返回日期时间列的格式。

For example I have a table titles例如我有一个表格标题

id (INT), title (VARCHAR), created_at (DATETIME)

and a row would be like this一行会是这样的

1,"Title 1","2019-02-03 12:13:14"

If I now do the following query如果我现在执行以下查询

SELECT JSON_OBJECT('title',title,'created_at',created_at) AS title_json FROM titles WHERE id = 1;

I will get the resulting title_json column as:我将得到的title_json列如下:

{
    "title": "Title 1",
    "created_at": "2019-02-03 12:13:14.000000"
}

I would like to have the datetime values returned in the standard YYYY-MM-DD HH:ii:ss format, without the trailing zeroes.我希望以标准YYYY-MM-DD HH:ii:ss格式返回日期时间值,不带尾随零。

Is this possible?这可能吗?

I have looked through the JSON_OBJECT documentation but couldn't find any clues to this mystery.我浏览了 JSON_OBJECT 文档,但找不到任何线索来解开这个谜团。 I'm thinking the format used might be defined somewhere in the server/database settings.我认为所使用的格式可能在服务器/数据库设置中的某处定义。 The ideal solution for my case would be to optionally set the desired format in individual queries themselves.对于我的情况,理想的解决方案是选择性地在各个查询中设置所需的格式。

I'm using: Server: MySQL Community Server (GPL) Version: 5.7.24我正在使用:服务器:MySQL 社区服务器 (GPL) 版本:5.7.24

You can use DATE_FORMAT您可以使用DATE_FORMAT

SELECT JSON_OBJECT('title',title,'created_at',
                    DATE_FORMAT(created_at, "%Y-%c-%d %H:%i:%s")) AS title_json 
  FROM titles 
 WHERE id = 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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