Reputation: 21
I want hour value only from the currenttime
Like if it is 4:31:13 so i want only 4 and that also should be in 12hrs format..
Please help me...
Upvotes: 0
Views: 218
Reputation: 7123
SELECT
case when DATEPART(hh, time) > 12
then DATEPART(hh, time) - 12
else DATEPART(hh, time) end as hour
from time;
Upvotes: 2
Reputation: 77677
SELECT (DATEPART(HOUR, GETDATE()) + 11) % 12 + 1
At 1 am this will return:
1 + 11 = 12; 12 % 12 = 0; 0 + 1 = 1
At 1 pm (13:00 in 24 hrs format) you'll get:
13 + 11 = 24; 24 % 12 = 0; 0 + 1 = 1
Similarly, at 2 am and at 2 pm (14:00):
2 + 11 = 13; 13 % 12 = 1; 1 + 1 = 2
14 + 11 = 25; 25 % 12 = 1; 1 + 1 = 2
and so on till 11 am and 11 pm. At 12 am (0:00) & 12 pm (12:00) it will go like this:
0 + 11 = 11; 11 % 12 = 11; 11 + 1 = 12
12 + 11 = 23; 23 % 12 = 11; 11 + 1 = 12
Upvotes: 1
Reputation: 902
This will also correctly handle 12 AM and 12 PM time:
select case datepart(hh, getdate())
when 0 then 12
when 12 then 12
else datepart(hh, getdate()) % 12
end;
Upvotes: 1
Reputation: 2041
SELECT SUBSTRING(LTRIM(RIGHT(CONVERT(VARCHAR(20), GETDATE(), 100), 7)),1,1)
Upvotes: 0
Reputation: 701
I don't know what database engine are you using, but in PostgreSQL you can do this:
select to_char(current_timestamp, 'HH12');
Upvotes: 0