Date format returned as mm/dd/yyyy hh:mm:ss AM/PM

隐身守侯 提交于 2020-01-03 07:37:42

问题


I am brand new to sql my company just kinda threw me head long into this and said do it. So any help is greatly appreciated. I am trying to get a date to come out in the format of mm/dd/yyyy hh:mm:ss AM/PM so for example a date of 09/26/2014 11:04:54 AM. I have tried using the code:

Select Convert(nvarchar,EntryDate,101)
From DB1

However that returns just 09/26/2014. I also tried

Select Convert(nvarchar,EntryDate,100)
From DB1

but this returns Sep 26 2014 11:04AM

Not sure where to go from here. Again thanks for the help. BTW I am using SQL Server 2012.


回答1:


Since you're on SQL 2012 the format function should work:

declare @date datetime = '2014-09-26 11:04:54'
select FORMAT(@date,'MM/dd/yyyy hh:mm:s tt')

result: 09/26/2014 11:04:54 AM

In your case it would be:

Select FORMAT(EntryDate,'MM/dd/yyyy hh:mm:s tt')
From DB1



回答2:


DECLARE @Date_Value DATETIME = GETDATE();


SELECT CONVERT(VARCHAR(10), @Date_Value, 101) + ' ' 
       + LTRIM(RIGHT(CONVERT(CHAR(20), @Date_Value, 22), 11))


RESULT: 09/26/2014 5:25:53 PM

Your Query

SELECT CONVERT(VARCHAR(10), EntryDate, 101) + ' ' 
       + LTRIM(RIGHT(CONVERT(CHAR(20), EntryDate, 22), 11))
From DB1



回答3:


    > select convert(varchar(20),GETDATE(),1)+' '+convert(varchar(20),convert(time,getdate()),100)
    > select convert(varchar(20),GETDATE(),103)+' '+convert(varchar(20),convert(time,getdate()),100)
    > select convert(varchar(20),GETDATE(),103)+' '+convert(varchar(20),convert(time,getdate()),22)


    > Result (1) :-  10/15/2018 11:22AM (mm/dd/yyyy hh:mm AM/PM)
    > Result (2):-  15/10/2018 11:22AM (dd/mm/yyyy hh:mm AM/PM)
    > Result (3):-  15/10/2018 11:22:35 AM (dd/mm/yyyy hh:mm:ss AM/PM)



回答4:


You can use FORMAT function in sql

SELECT FORMAT(@date,'MM/dd/yyyy hh:mm:s tt')



回答5:


You should do this to convert a date in the format you ask for DATE_FORMAT(date,'%m %d %Y %h:%i %p'). Where date is the date you want converted.

I hope this helps.




回答6:


USING two formats and concatenating them with REPLACE and SUBSTRING functions.

   select CONVERT(nvarchar(128), dbo.GetDateTime(@input), 101) + 
           REPLACE(SUBSTRING(CONVERT(nvarchar(128), 
           dbo.GetDateTime(@input), 109), 12 , 128),':000', ' ')



回答7:


Combining two formats:

select convert(char(11),getdate(),103) 
      + stuff(right(convert(char(31),getdate(),130),14),9,4,' ')

yields:

26/09/2014 12:29:09 PM



回答8:


As yet another way to solve the same problem this works.

Select Convert(char(10), getdate(),101) + Right(Convert(VarChar(20),getdate(),100),8)


来源:https://stackoverflow.com/questions/26063902/date-format-returned-as-mm-dd-yyyy-hhmmss-am-pm

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