there are date values in the below format,in one of the sql server 2000 tables
10/1/2013 10:39:14 PM
10/1/2013 6:39:04 PM
10/1/2013 8:19:31 AM
10/1/2013 3:35:40 AM
how to convert the above format data values into a 24hour date format,as shown below
10/1/2013 10:39
10/1/2013 18:39
10/1/2013 8:19
10/1/2013 3:35
Try this:
First convert varchar date to datetime and then you can manipulate it in the way you want as:
-- CONVERT TO DATETIME TO GET 24HR FORMAT
SELECT CONVERT(DATETIME, '10/1/2013 6:39:04 PM', 0)
-- Concatenate in required format
SELECT CONVERT(VARCHAR(10), CONVERT(DATETIME, '10/1/2013 6:39:04 PM', 0), 101)
+ ' '+ CONVERT(VARCHAR(5),CONVERT(DATETIME, '10/1/2013 6:39:04 PM', 0), 108)
user5502892
In SQL Server 2012, we can use Format function to have suitable date time format. Use capital letter 'HH:mm:ss' for 24 hour date time format.
Example -
Query (24 hour format):
Select Format(cast('2016-03-03 23:59:59' as datetime),'dd-MMM-yyyy HH:mm:ss','en-us'). ('HH:mm:ss' in Capital letters)
Result
03-Mar-2016 23:59:59
Query (12 hour format):
Select Format(cast('2016-03-03 23:59:59' as datetime),'dd-MMM-yyyy hh:mm:ss','en-us'). ('hh:mm:ss' in Capital letters)
Result
03-Mar-2016 11:59:59
Declare @s DateTime = '2012-12-26 11:00:00.000 PM'
select stuff(convert(varchar(19), @s, 126),11,1,' ')
declare @Hour_Part AS VARCHAR(50)
declare @Min_Part AS VARCHAR(50)
declare @Sec_Part AS VARCHAR(50)
declare @PMORAM AS VARCHAR(5)
SELECT @Hour_Part = DATEPART(HOUR,CONVERT(VARCHAR(50),GETDATE(),108))
SELECT @PMORAM = RIGHT(CONVERT(VARCHAR(30), GETDATE(), 9), 2)
IF @Hour_Part = 12 AND @PMORAM = 'AM'
BEGIN
SET @Hour_Part = '00'
select @Min_Part = DATEPART(MINUTE,CONVERT(VARCHAR(50),GETDATE(),108))
select @Sec_Part = DATEPART(SECOND,CONVERT(VARCHAR(50),GETDATE(),108))
select @Hour_Part + ':' + @Min_Part + ':' + @Sec_Part AS DateTime24
END
ELSE IF @Hour_Part > 0 AND @Hour_Part < 12 AND @PMORAM = 'PM'
BEGIN
SET @Hour_Part = @Hour_Part + 12
select @Min_Part = DATEPART(MINUTE,CONVERT(VARCHAR(50),GETDATE(),108))
select @Sec_Part = DATEPART(SECOND,CONVERT(VARCHAR(50),GETDATE(),108))
select @Hour_Part + ':' + @Min_Part + ':' + @Sec_Part AS DateTime24
END
ELSE
BEGIN
select @Min_Part = DATEPART(MINUTE,CONVERT(VARCHAR(50),GETDATE(),108))
select @Sec_Part = DATEPART(SECOND,CONVERT(VARCHAR(50),GETDATE(),108))
select @Hour_Part + ':' + @Min_Part + ':' + @Sec_Part AS DateTime24
END
try this
DECLARE @MyDateTime;
SET @MyDateTime = '2016-03-03 23:59:59'
SELECT FORMAT(CONVERT(DATETIME,@MyDateTime,108),'dd-MMM-yyyy HH:mm:ss','en-us')
来源:https://stackoverflow.com/questions/19563261/convert-a-12-hour-format-to-24-hour-format-in-sql-server