简体   繁体   中英

Converting date time format

We have data in a Visit_Time column stored in 24Hrs date format as well as 12Hrs.

The data is inserted into a table from a different type of source like MobileApp and Web source etc.

Example:

Create table VisitorDetails
(
  Visit_Date Date,
  Visit_Time varchar(12)
)

VisitorDetails
----------------------------
Visit_Date      Visit_Time 
----------------------------
2020-01-01       01:00PM
2020-01-02       17:00
2020-01-03       04:00PM
2020-01-04       20:00
-----------------------------

How to convert Visit_Time Column either in 12 Hrs format or 24 Hrs formate?

Need Result like below

VisitorDetails     12Hrs                  24Hrs
----------------------------           --------------
Visit_Date      Visit_Time      (OR)     Visit_Time
----------------------------           --------------
2020-01-01       01:00PM                   13:00              
2020-01-02       05:00PM                   17:00              
2020-01-03       04:00PM                   16:00
2020-01-04       08:00PM                   20:00
-----------------------------          --------------

Please try below solution:

--24 Hour Format
SELECT  CONVERT(VARCHAR(5),CONVERT(DATETIME, '01:00PM', 0), 108) 
SELECT  CONVERT(VARCHAR(5),CONVERT(DATETIME, '17:00', 0), 108) 

--12 Hour Format
SELECT LTRIM(RIGHT(CONVERT(VARCHAR(20), CONVERT(DATETIME, '01:00PM', 0), 100), 7))
SELECT LTRIM(RIGHT(CONVERT(VARCHAR(20), CONVERT(DATETIME, '17:00', 0), 100), 7))
12 hour format

declare @t1 time
declare @t2 time
declare @t3 time

set @t1 = '14:40'
set @t2 = '17:00'
set @t3 = '01:00PM'

select CONVERT(varchar(15),@t1,100)
select CONVERT(varchar(15),@t2,100)
select CONVERT(varchar(15),@t3,100)

When fetching your rows you could do:

SELECT [Visit_Date], LEFT(PARSE([Visit_Time] AS time), 5)
FROM [VisitorDetails]

for a consistent time format. However, I would strongly recommend returning time values from the db and do the display modification in your app.

To Store 24 hrs format declare the Column data type as DATETIME Instead of Varchar(12)

DECLARE @T TABLE(
ID INT IDENTITY(1,1),
Visit_DATE_TIME varchar(20))

12 hrs Data insertion:

INSERT INTO @T VALUES('24-MAY-2020 10:30PM')
INSERT INTO @T VALUES('25-MAY-2020 11:30AM')

24 hrs Data insertion:

INSERT INTO @T VALUES('26-MAY-2020 16:30')
INSERT INTO @T VALUES('28-MAY-2020 22:30')

Query

SELECT *, CAST(VISIT_DATE_TIME as DATE) as Visit_Date ,
CAST(VISIT_DATE_TIME as TIME) as Visit_Time_24,
RIGHT(CONVERT(DATETIME,RTRIM(VISIT_DATE_TIME), 109),7) as Visit_Time_12
FROM @T 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM