Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a 12 hour format to 24 hour format in sql server

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
like image 253
user1254579 Avatar asked Oct 24 '13 10:10

user1254579


2 Answers

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
like image 151
user5502892 Avatar answered Sep 20 '22 19:09

user5502892


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)
like image 24
Deepshikha Avatar answered Sep 21 '22 19:09

Deepshikha