How to display the date as mm/dd/yyyy hh:mm Am/PM using sql server 2008 r2?

若如初见. 提交于 2020-01-20 18:42:49

问题


My sample query is

SELECT D30.SPGD30_LAST_TOUCH_Y
from CSPGD30_TRACKING D30 

My given date format is like "2013-01-01 00:00:00.000". I need to convert this date format to "mm/dd/yyyy hh:mm AM/PM". Do you have any idea about that?


回答1:


I think there is no single format to give them both. Try this using Convert; Sql-Demo

declare @mydate datetime = getdate()
select convert(varchar(10),@mydate, 101) + right(convert(varchar(32),@mydate,100),8)

|           COLUMN_0 |
----------------------
| 02/22/2013  9:36AM |



回答2:


The FORMAT() function is available from version 2012 onwards. Once upgraded, you can use

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



回答3:


Use this

select CONVERT(VARCHAR(10), mydate, 101) + ' ' + RIGHT(CONVERT(VARCHAR, mydate, 100), 7) from tablename



回答4:


Try this

 SELECT convert(varchar(20), GetDate(), 0);

To extract only AM/PM

substring(convert(varchar(30), GetDate(), 9), 25, 2);

Fiddle




回答5:


Use the following scenario for getting date,time,day,month,year,hours,minutes,seconds,AM/PM

:)

SELECT UpdatedOn ,
  CONVERT(varchar,UpdatedOn,100) DateTime,
  CONVERT(varchar,UpdatedOn,10) Date ,
  CONVERT(varchar,UpdatedOn,108) Time ,
  substring(CONVERT(varchar,UpdatedOn,106),1,2) Day,
  substring(CONVERT(varchar,UpdatedOn,106),4,3) CMonth,
  substring(CONVERT(varchar,UpdatedOn,105),4,2) NMonth,
  substring(CONVERT(varchar,UpdatedOn,106),8,4) Year,
  left(right(CONVERT(varchar,UpdatedOn,100),7),2) Hours_12,
  substring(CONVERT(varchar,UpdatedOn,108),1,2) Hours_24,
  substring(CONVERT(varchar,UpdatedOn,108),4,2) Minutes,
  substring(CONVERT(varchar,UpdatedOn,108),7,2) Second,
  right(CONVERT(varchar,UpdatedOn,100),2) AM_PM 
FROM dbo.DeviceAssignSim 
WHERE AssignSimId=55;



回答6:


You can do it like this:

SELECT CONVERT(VARCHAR(10), GETDATE(), 101) AS [MM/DD/YYYY]

For more information look this:

date-format




回答7:


Use the convert method to format a datetime value. Example:

select convert(varchar(20), D30.SPGD30_LAST_TOUCH_Y, 101)

The third parameter determines the format. You can find the available formats in the cast and convert documentation.



来源:https://stackoverflow.com/questions/15020865/how-to-display-the-date-as-mm-dd-yyyy-hhmm-am-pm-using-sql-server-2008-r2

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