How do I format date in TSql when I use json_value

六眼飞鱼酱① 提交于 2020-01-04 05:19:09

问题


I am using SQL Server 2016 and I am storing json. When I extract it, the datetime format does not show clean. How do I format the datetime format?

select 
    JSON_VALUE(trade, '$.entrytime') AS entrytime 
from 
    dbo.Trades

Values shown:

2016-05-23T05:21:30.3068919-04:00
2016-05-24T10:49:16.337257-04:00
2016-05-24T11:05:30.8941267-04:00
2016-05-24T11:37:35.9555731-04:00

How do I format those dates in the yyyy-mm-dd hh:mm:ss format?


回答1:


You can also use FORMAT:

select FORMAT(CAST(JSON_VALUE(trade, '$.entrytime') as datetimeoffset), 'yyyy-MM-dd hh:mm:ss') AS entrytime from dbo.Trades



回答2:


You want to format the following timestamp to look like the one following it:

2016-05-24T11:37:35.9555731-04:00
2016-05-24 11:37:35

The following query replaces the T with a space, and also substrings off everything which comes after (and including) the period.

SELECT REPLACE(SUBSTRING(JSON_VALUE(trade, '$.entrytime'), 1,
                         CHARINDEX('.', JSON_VALUE(trade, '$.entrytime')) - 1),
               'T', ' ') AS entrytime
FROM dbo.Trades


来源:https://stackoverflow.com/questions/37450492/how-do-i-format-date-in-tsql-when-i-use-json-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!