Converting datetime format to 12 hour - sql

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

Related

Date conversion for YY-Monthtext to MM/DD/YYYY

Receive date as "19-May" and need to convert it as '05/01/2019', "19-June" to '06/01/2019'.
I have tried various date conversion but it didn't work.
You can try this. Storing date in this format is not a good/suggestion you should use the proper data type which are meant and available for.
You should update the values with proper date time value and then change the data type also. It will save your time & you do not need these conversions every time.
Select Try_Cast('19-May 2019' as Datetime)
OR
Select Try_Cast('19-May' + '2019' as Datetime)
To get the first date of month you can try the below query.
SELECT DATEADD(month, DATEDIFF(month, 0, Try_Cast('19-May 2019' as Datetime)), 0) AS StartOfMonth
Edit
To get the first date of month as per the given data in string, you can use the below query.
declare #dateinStr varchar(20) = '19-May'
Select try_cast('01-' + Replace(#dateinStr, LEFT(#dateinStr, 3), '') + LEFT(#dateinStr, 2) as Datetime) as Date
Here is the demo.
I suppose the months will be 3 chars only, if so then
Select s,
try_Cast(concat(right(s, 3), ' 2019') as Datetime)
from
(
values
('19-May'),
('19-Jun')
) t(s);
If the months is really comes like "June" & "August" then
select s,
try_cast(concat(substring(s, charindex('-',s)+1, 3), ' 2019') as date)
from
(
values
('19-May'),
('19-June'),
('15-August')
) t(s);
If you need to format it as mm/dd/yyyy then use 101 style.
You can do :
SELECT DATEADD(DAY, 1, EOMONTH(CONVERT(DATE, Dates + '-2019'), -1))
FROM ( VALUES ('19-May'), ('19-June')
) t(Dates);

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)

DATEDIFF in HH:MM:SS format

I need to calculate the total length in terms of Hours, Minutes, Seconds, and the average length, given some data with start time and end time.
For example the result must be something like 45:15:10 which means 45 hours 15 min 10 sec, or 30:07 for 30 min 07 sec.
We're using SQL Server 2008 R2 and the conversion failed when time is more than 24:59:59. Any idea of how I could do this?
For information, the columns in the table are Id, StartDateTime, EndDateTime, etc. I need to make a monthly report which contains the recordings count of the month, the total length of these records, and the average length. I'd like to know if there is an easy way to perform all of this.
You shouldn't be converting to time - it is meant to store a point in time on a single 24h clock, not a duration or interval (even one that is constrained on its own to < 24 hours, which clearly your data is not). Instead you can take the datediff in the smallest interval required (in your case, seconds), and then perform some math and string manipulation to present it in the output format you need (it might also be preferable to return the seconds to the application or report tool and have it do this work).
DECLARE #d TABLE
(
id INT IDENTITY(1,1),
StartDateTime DATETIME,
EndDateTime DATETIME
);
INSERT #d(StartDateTime, EndDateTime) VALUES
(DATEADD(DAY, -2, GETDATE()), DATEADD(MINUTE, 15, GETDATE())),
(GETDATE() , DATEADD(MINUTE, 22, GETDATE())),
(DATEADD(DAY, -1, GETDATE()), DATEADD(MINUTE, 5, GETDATE())),
(DATEADD(DAY, -4, GETDATE()), DATEADD(SECOND, 14, GETDATE()));
;WITH x AS (SELECT id, StartDateTime, EndDateTime,
d = DATEDIFF(SECOND, StartDateTime, EndDateTime),
a = AVG(DATEDIFF(SECOND, StartDateTime, EndDateTime)) OVER()
FROM #d
)
SELECT id, StartDateTime, EndDateTime,
[delta_HH:MM:SS] = CONVERT(VARCHAR(5), d/60/60)
+ ':' + RIGHT('0' + CONVERT(VARCHAR(2), d/60%60), 2)
+ ':' + RIGHT('0' + CONVERT(VARCHAR(2), d % 60), 2),
[avg_HH:MM:SS] = CONVERT(VARCHAR(5), a/60/60)
+ ':' + RIGHT('0' + CONVERT(VARCHAR(2), a/60%60), 2)
+ ':' + RIGHT('0' + CONVERT(VARCHAR(2), a % 60), 2)
FROM x;
Results:
id StartDateTime EndDateTime delta_HH:MM:SS avg_HH:MM:SS
-- ------------------- ------------------- -------------- ------------
1 2013-01-19 14:24:46 2013-01-21 14:39:46 48:15:00 42:10:33
2 2013-01-21 14:24:46 2013-01-21 14:46:46 0:22:00 42:10:33
3 2013-01-20 14:24:46 2013-01-21 14:29:46 24:05:00 42:10:33
4 2013-01-17 14:24:46 2013-01-21 14:25:00 96:00:14 42:10:33
This isn't precisely what you asked for, as it won't show just MM:SS for deltas < 1 hour. You can adjust that with a simple CASE expression:
;WITH x AS (SELECT id, StartDateTime, EndDateTime,
d = DATEDIFF(SECOND, StartDateTime, EndDateTime),
a = AVG(DATEDIFF(SECOND, StartDateTime, EndDateTime)) OVER()
FROM #d
)
SELECT id, StartDateTime, EndDateTime,
[delta_HH:MM:SS] = CASE WHEN d >= 3600 THEN
CONVERT(VARCHAR(5), d/60/60) + ':' ELSE '' END
+ RIGHT('0' + CONVERT(VARCHAR(2), d/60%60), 2)
+ ':' + RIGHT('0' + CONVERT(VARCHAR(2), d % 60), 2),
[avg_HH:MM:SS] = CASE WHEN a >= 3600 THEN
CONVERT(VARCHAR(5), a/60/60) + ':' ELSE '' END
+ RIGHT('0' + CONVERT(VARCHAR(2), a/60%60), 2)
+ ':' + RIGHT('0' + CONVERT(VARCHAR(2), a % 60), 2)
FROM x;
This query changes the delta column in the 2nd row in the above result from 0:22:00 to 22:00.
I slightly modified Avinash's answer as it may end with error if difference is too big. If you need only HH:mm:ss it is sufficient to distinguish at seconds level ony like this:
SELECT CONVERT(time,
DATEADD(s,
DATEDIFF(s,
'2018-01-07 09:53:00',
'2018-01-07 11:53:01'),
CAST('1900-01-01 00:00:00.0000000' as datetime2)
)
)
SELECT CONVERT(time,
DATEADD(mcs,
DATEDIFF(mcs,
'2007-05-07 09:53:00.0273335',
'2007-05-07 09:53:01.0376635'),
CAST('1900-01-01 00:00:00.0000000' as datetime2)
)
)
If you want to do averages, then the best approach is to convert to seconds or fractions of a day. Day fractions are convenient in SQL Server, because you can do things like:
select avg(cast(endtime - starttime) as float)
from t
You can convert it back to a datetime using the reverse cast:
select cast(avg(cast(endtime - starttime as float) as datetime)
from t
The arithmetic to get the times in the format you want . . . that is a pain. You might consider including days in the final format, and using:
select right(convert(varchar(255), <val>, 120), 10)
To get the hours exceeding 24, here is another approach:
select cast(floor(cast(<val> as float)*24) as varchar(255))+right(convert(varchar(255), <val>, 120), 6)
It uses convert for minutes and seconds, which should be padded with 0s on the left. It then appends the hours as a separate value.
Starting in SQL SERVER 2012, you don't need to use DATEDIFF function. You can use FORMAT function to achieve what you want:
SELECT
FORMAT(CONVERT(TIME, [appoitment].[Start] - [appointment].[End]), N'hh\:mm') AS 'Duration'
FROM
[tblAppointment] (NOLOCK)
A way that avoids overflows and can include days and go all the way to milliseconds in the output:
DECLARE #startDate AS DATETIME = '2018-06-01 14:20:02.100'
DECLARE #endDate AS DATETIME = '2018-06-02 15:23:09.000'
SELECT CAST(DATEDIFF(day,'1900-01-01', #endDate - #startDate) AS VARCHAR) + 'd ' + CONVERT(varchar(22), #endDate - #startDate, 114)
The above will return
1d 01:03:06:900
And, off course, you can use the formatting of your choice
SQL Supports datetime substraction which outputs a new datetime relative to the MIN date (for instance 1900-01-01, you can probably get this value from some system variable) This works better than DATEDIFF, because DATEDIFF will count ONE for each "datepart boundaries crossed", even if the elapsed time is less than a whole datapart. Another nice thing about this method is that it allows you to use the date formatting conversions.
If days is the (positive) number of days, like 0.5 for 12 hours, use this expression to format it as a proper duration:
CONVERT(varchar(9), FLOOR(days * 24)) + RIGHT(CONVERT(char(19), CAST(days AS datetime), 120), 6)
Excel will understands values up to 9999:59:59 when pasted. There apply a custom format: [h]:mm:ss in the English version ([u]:mm:ss for Dutch).

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

SQL DATETIME Math

I am trying to do the following:
Format GetDate() to display only the minutes
Format a varchar column to display only the minutes
Subtract the current time HH:MM:SS from GetDate() and the VarChar column
This is what I have
CONVERT(VARCHAR(5), GETDATE(), 108) - substring(convert(varchar(20), ColumnName, 9), 13, 5)
but I am getting this error and need some help please:
Operand data type varchar is invalid for subtract operator.
What you want is datepart(mi).
To get the minutes for getdate():
select datepart(mi, getdate())
To subtract a number of minutes from a datetime:
select dateadd(mi, - <minutes>, <datevalue>)
To remove the time from getdate(), just cast to date (in more recent versions of SQL Server):
select cast(getdate() as date)
To get the difference in minutes, use datediff:
select datediff(mi, <datestart>, <dateend>)
What are you really trying to accomplish?
I think this is what you want:
declare #str varchar(30)
set #str = '2012-08-14 10:12:02.690'
select datediff(minute, cast(#str as datetime), getdate())
Results when getdate() = '2012-08-14 11:21:10.250' is total minutes even over 60:
69