Convert VARCHAR 24 Hour Time to 12 Hour - sql

I have a 24 hour time, start_time, that is stored as varchar (no control over this). I need to convert it to 12 hour with AM/PM.
Examples:
17:45 should become 5:45 PM
09:00 should become 9:00 AM

Do multi conversations :
select convert(varchar(20), convert(time(0), start_time), 100)
from table t;
EDIT :
Use apply :
select stuff(time_c, len(time_c)-1, 0, ' ')
from table t cross apply
( values (convert(varchar(20), convert(time(0), start_time), 100))
) t(time_c)

With a space between the time and AM/PM:
select replace(replace(convert(varchar(8), convert(time(0), '09:00'), 100),'A',' A'),'P',' P')

It is easy with FORMAT function:
SELECT timestr
, FORMAT(CONVERT(DATETIME, timestr, 108), 'h:mm t')
, FORMAT(CONVERT(DATETIME, timestr, 108), 'h:mm tt')
FROM (VALUES
('17:45'),
('09:00')
) t(timestr)
Note that tt format specifier does not work with time datatype.

You really should be fixing your design and I strongly suggest you do. The time data type exists for a reason, and the format of the value should be determined in the presentation layer, not in the RDBMS. If, you have to conver into the RDBMS in an inferior format, then you would need to CONVERT to time, and then back to varchar and use some string manipulation:
SELECT V.YourTime,
STUFF(NewTime, LEN(NewTime)-4,3,' ') AS NewTime
FROM (VALUES('09:00'),('17:45'))V(YourTime)
CROSS APPLY(VALUES(CONVERT(varchar(10),CONVERT(time(0),V.YourTime),109)))C(NewTime);
DB<>Fiddle

Related

How can i pull only Hour Number with AM/PM in SQL SERVER

My Input :
2020-01-01 09:01:00.000
2020-01-03 18:01:00.000
My Output Should be like :
9 AM
6 PM
You can use the format function like this as long as you're using SQL Server 2012 or later.
SELECT FORMAT(GETDATE(),'h tt') AS MyTime
Note the use of the lower case 'h' which gives a 12 hour clock with no leading zero, 'HH' gives a two digit 24 hour clock so you end up with output like '16 PM'.
If the input is a date-related type, you can use FORMAT with the appropriate format string, eg :
SELECT FORMAT(getdate(), 'HH:mm tt')
For me, this returns :
12:51 PM
Just HH tt returns the desired string, in this case :
12 PM
You can do conversion :
SELECT CONVERT(varchar(10), CONVERT(TIME, '2020-01-01 09:01:00.000'), 100)
I would do:
SELECT V.YourColumn,
LTRIM(SUBSTRING(ca.v,13,2) + ' ' RIGHT(ca.v,2))
FROM (VALUES(CONVERT(Datetime2(3),'2020-01-01 09:01:00.000')),
(CONVERT(Datetime2(3),'2020-01-03 18:01:00.000')))V(YourColumn)
CROSS APPLY (VALUES(CONVERT(varchar(30),V.YourColumn,0))) ca(v);
In the CROSS APPLY I convert the datetime to the format MMM d YYYY h:mmAM/PM, then you can use SUBSTRING/LEFT to get the bits you want.
An alternative approach would be to use DATEPART:
SELECT CONCAT(CASE DATEPART(HOUR,V.YourColumn) WHEN 12 THEN 12 WHEN 0 THEN 12 ELSE DATEPART(HOUR,V.YourColumn) % 12 END,' ', RIGHT(CONVERT(varchar(30),V.YourColumn,0),2))
FROM (VALUES(CONVERT(Datetime2(3),'2020-01-01 09:01:00.000')),
(CONVERT(Datetime2(3),'2020-01-03 00:01:00.000')),
(CONVERT(Datetime2(3),'2020-01-03 18:01:00.000')))V(YourColumn);
Because 12 % 12 and 0 % 12 both = 0, then you need the CASE expression to handle those.
Your query.
SELECT convert(VARCHAR(30), cast('2020-01-01 09:01:00.000' AS DATETIME), 100)
,convert(VARCHAR(30), cast('2020-01-03 18:01:00.000' AS DATETIME), 100)

Convert ISO-8601 varchar (0000-00-00T00:00:00+00:00) to datetime in SQL

How can I convert 2019-07-01T00:00:00+05:30 to DateTime in SQL?
2019-07-01T00:00:00+05:30 is a varchar field. I need to convert this into DateTime to compare this to a date field.
suggest me a query to Convert (2019-07-01T00:00:00+05:30) into DateTime
Convert To date :
select cast('2019-07-01T00:00:00+05:30' as Date)
Convert To time:
select cast('2019-07-01T00:00:00+05:30' as Time)
Convert To datetime :
select convert(datetime2, '2019-07-01T10:00:30+05:30',0)
Try any of these..
select cast(convert(datetime2, '2019-07-01T10:00:30+05:30',0) as datetime)
select convert(datetime2, '2019-07-01T10:00:30+05:30',0)
One option would be to use a combination of CONVERT on the timestamp without the timezone component, then use TODATETIMEOFFSET with the timezone portion to get the final result:
WITH yourTable AS (
SELECT '2019-07-01T00:00:00+05:30' AS dt
)
SELECT
TODATETIMEOFFSET(CONVERT(datetime, LEFT(dt, 19), 126), RIGHT(dt, 6)) AS output
FROM yourTable;
This outputs:
01/07/2019 00:00:00 +05:30
Demo
Unfortunately, SQL Server truncates the time zone information when converting from datetimeoffset to dateordatetime`. But, you can calculate the offset and add it back in:
select dateadd(minute,
datediff(minute, convert(datetimeoffset, dt), convert(datetime, convert(datetimeoffset, dt))),
convert(datetime, convert(datetimeoffset, dt))
)
from (values ('2019-07-01T00:00:00+05:30')) v(dt);
For your particular timezone, the date at midnight matches the UTC date, so you are safe. I'm on the other side of the world, so this would be a more important consideration in the "western" world ("west" being west of UTC).
The following query will convert the given VARCHAR to DATETIME value:
DECLARE #DateVal AS VARCHAR (30) = '2019-07-01T00:00:00+05:30';
SELECT CAST(REPLACE(SUBSTRING(#DateVal, 0, CHARINDEX('+', #DateVal)), 'T', ' ') AS DATETIME);

How do I convert time into an integer in SQL Server

I have a date column and a time column that are integers
I converted the date portion like this
select convert(int, convert(varchar(10), getdate(), 112))
I thought I could do the same with this query that gives the time in HH:mm:ss
SELECT CONVERT(VARCHAR(8), GETDATE(), 108)
How do I convert just the time into an integer?
This should convert your time into an integer representing seconds from midnight.
SELECT (DATEPART(hour, Col1) * 3600) + (DATEPART(minute, Col1) * 60) + DATEPART(second, Col1) as SecondsFromMidnight FROM T1;
Assuming you are looking for the "time" analogy to the "date" portion of your code which takes YYYYMMDD and turns it into an INT, you can:
start with the HH:mm:ss format given by the style number 108
remove the colons to get that string into HHmmss
then convert that to INT
For example:
SELECT REPLACE(
CONVERT(VARCHAR(8), GETDATE(), 108),
':',
''
) AS [StringVersion],
CONVERT(INT, REPLACE(
CONVERT(VARCHAR(8), GETDATE(), 108),
':',
''
)
) AS [IntVersion];
You can use the differece between midnight and the time of the day. For example, using getdate(), you can know the percentage of the time of the day with this query:
select convert(float,getdate()-convert(date,getdate()))
You can then convert this number to seconds
select convert(int,86400 * convert(float,getdate()-convert(date,getdate())))
You'll get the number of seconds from midnight
I think this is easier to understand when using with a SQL Update statement.
UPDATE dbo.MyTable
SET TIME_AS_INT = CAST(REPLACE(CAST(CONVERT(Time(0), GETDATE()) AS varchar),':','') AS INT)
To add/subtract time from the result before converting use dateadd()
SELECT CAST(REPLACE(CAST(CONVERT(Time(0), dateadd(MINUTE, 1, getdate())) AS varchar),':','') AS INT)

Get Hours and Minutes (HH:MM) from date

I want to get only hh:mm from date.
How I can get this?
I have tried this :
CONVERT(VARCHAR(8), getdate(), 108)
Just use the first 5 characters...?
SELECT CONVERT(VARCHAR(5),getdate(),108)
You can easily use Format() function instead of all the casting for sql 2012 and above only
SELECT FORMAT(GETDATE(),'hh:mm')
This is by far the best way to do the required conversion.
Another method using DATEPART built-in function:
SELECT cast(DATEPART(hour, GETDATE()) as varchar) + ':' + cast(DATEPART(minute, GETDATE()) as varchar)
If you want to display 24 hours format use:
SELECT FORMAT(GETDATE(),'HH:mm')
and to display 12 hours format use:
SELECT FORMAT(GETDATE(),'hh:mm')
Following code shows current hour and minutes in 'Hour:Minutes' column for us.
SELECT CONVERT(VARCHAR(5), GETDATE(), 108) +
(CASE WHEN DATEPART(HOUR, GETDATE()) > 12 THEN ' PM'
ELSE ' AM'
END) 'Hour:Minutes'
or
SELECT Format(GETDATE(), 'hh:mm') +
(CASE WHEN DATEPART(HOUR, GETDATE()) > 12 THEN ' PM'
ELSE ' AM'
END) 'Hour:Minutes'
The following works on 2008R2+ to produce 'HH:MM':
select
case
when len(replace(replace(replace(right(cast(getdate() as varchar),7),'AM',''),'PM',''),' ','')) = 4
then '0'+ replace(replace(replace(right(cast(getdate() as varchar),7),'AM',''),'PM',''),' ','')
else replace(replace(replace(right(cast(getdate() as varchar),7),'AM',''),'PM',''),' ','') end as [Time]
You can cast datetime to time
select CAST(GETDATE() as time)
If you want a hh:mm format
select cast(CAST(GETDATE() as time) as varchar(5))
Here is syntax for showing hours and minutes for a field coming out of a SELECT statement. In this example, the SQL field is named "UpdatedOnAt" and is a DateTime. Tested with MS SQL 2014.
SELECT Format(UpdatedOnAt ,'hh:mm') as UpdatedOnAt from MyTable
I like the format that shows the day of the week as a 3-letter abbreviation, and includes the seconds:
SELECT Format(UpdatedOnAt ,'ddd hh:mm:ss') as UpdatedOnAt from MyTable
The "as UpdatedOnAt" suffix is optional. It gives you a column heading equal tot he field you were selecting to begin with.
TO_CHAR(SYSDATE, 'HH')
I used this to get the current hour in apex PL/SQL

Converting datetime format to 12 hour

I have this query
select CONVERT(varchar(5), tdate ,108) AS [Time] from table
which gives me the time in 24 hour format( military)
I wanted to convert it into a 12 hour format so i tried the query below
select SUBSTRING(CONVERT(VARCHAR, tdate, 100),13,2) + ':'
+ SUBSTRING(CONVERT(VARCHAR, tdate, 100),16,2) + ''
+ SUBSTRING(CONVERT(VARCHAR, tdate, 100),18,2) AS T
from table
and i get the 12 hour format but I am just curious if there is a shorter or better way of doing it. any help?
If you want to convert the current datetime for example:
SELECT CONVERT(VARCHAR, getdate(), 100) AS DateTime_In_12h_Format
Instead of getdate() you can put your desired column in a query (such as tdate in your example). If you want JUST the time in 12h and not the date and time use substring/right to separate them. It seems that you already know how to =).
This page lists every datetime conversion. It's really handy if you need other types of conversions.
This will return just the time, not the date.
SELECT RIGHT(CONVERT(VARCHAR, getdate(), 100), 7) AS time
For your table data:
select RIGHT(CONVERT(varchar, tdate ,100), 7) AS [Time] from table
Below code will return only time like 10:30 PM
SELECT FORMAT(CAST(getdate() AS DATETIME),'hh:mm tt') AS [Time]
Get date of server
SELECT LTRIM(RIGHT(CONVERT(VARCHAR(20), GETDATE(), 100), 7))
or
If it is stored in the table
SELECT LTRIM(RIGHT(CONVERT(VARCHAR(20), datename, 100), 7))
Result:
11:41AM
ifnull(date_format(at.date_time,'%d/%m/%Y'),"") AS date_time,
ifnull(time_format(at.date_time ,'%h:%i:%s'),"") AS date_time
This is how a SQL procedure looks...(for separating date and time)..there is no need of a special column for time/date....
Note:if H instead of h it will show the "hour in 24 hour" format