How do I convert hh:mm:ss to hh:mm in SQL Server? - sql

How do I convert hh:mm:ss to hh:mm in SQL Server?
select Count(Page) as VisitingCount,Page,CONVERT(VARCHAR(8),Date, 108) from scr_SecuristLog
where Date between '2009-05-04 00:00:00' and '2009-05-06 14:58'
and [user] in(select USERNAME
from scr_CustomerAuthorities )
group by Page,Date order by [VisitingCount] asc

CONVERT(VARCHAR(5),Date, 108)-- Gets only HH:mm

In general, the set of timestamps is not well-ordered, this means you cannot get a "last" timestamp whose time part up to minutes is 2009-05-06 14:58.
In SQL Server, which keeps the time part of a datetime as a number of 1/300 second fractions after midnight, this "last" timestamp would be 2009-05-06 14:58:59.997, but this is not guaranteed to be compatible with future releases of with other TIMESTAMP storage methods.
That means you'll need to split your BETWEEN condition into two conditions, one of which being strict less than the next minute:
select Count(Page) as VisitingCount,Page,CONVERT(VARCHAR(8),Date, 108) from scr_SecuristLog
where Date >= '2009-05-04 00:00:00'
AND Date < DATEADD(minute, 1, '2009-05-06 14:58')
and [user] in(select USERNAME
from scr_CustomerAuthorities )
group by Page,Date order by [VisitingCount] asc
This solution will efficiently use indexes on Date

SELECT Convert(varchar(5), GetDate(), 108)
Using varchar(5) will automatically truncate the date to remove the seconds.

I dont think there is a built in function; usually do something like this
SET #time = '07:45'
SET #date = CONVERT(DATETIME,#time)
SELECT #date
SELECT LEFT(CONVERT(VARCHAR,#date,108),5)

For this specific need you should use the between method as noted by Quassnoi's answer. However, the general problem can be solved with:
select dateadd(second, -datepart(second, #date), #date)

One way would be to use the RIGHT() function to crop the Date. Something like:
RIGHT(CONVERT(VARCHAR(8),Date, 108),5)
This will only work if number of characters is constant e.g. there is a leading zero if applicable. (Sorry havn't got SQL server here to test).
A better way is to use the T-SQL datepart function to split and then re-concatinate the date parts so:
DARTPART("hh", CONVERT(VARCHAR(8),Date, 108))+":"+DARTPART("mi", CONVERT(VARCHAR(8),Date, 108))
References:
http://msdn.microsoft.com/en-us/library/ms174420.aspx
http://msdn.microsoft.com/en-us/library/ms187928.aspx
http://msdn.microsoft.com/en-us/library/ms177532.aspx

To get hh:mm format from today's date:
select getdate()
select convert(varchar(5),getdate(),108)
To get hh:mm format from any datetime column in a table data:
select date_time_column_name from table_name where column_name = 'any column data name'
select convert(varchar(5),date_time_column_name,108) from table_name
where column_name = 'any column data name'
select creationdate from employee where Name = 'Satya'
select convert(varchar(5),creationdate,108) from employee
where Name = 'Satya'

SELECT CAST(CAST(GETDATE() AS Time(0)) AS VARCHAR(5))

Related

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);

SQL Server - How to convert varchar to date

I have a table containing StartDate in the format dd/mm/yyyy and yyyy-mm-dd.
I want to convert this varchar column to DATE type in the format DD/MM/YYYY.
I have tried the below.
select CONVERT(varchar(20),StartDate,103) AS [FormattedDate]
and
CONVERT(VARCHAR(20),(CAST([StartDate] AS DATE)),103)
I get the error -Conversion failed when converting date and/or time from character string.
Pls suggest.
if you only have the date string in dd/mm/yyyy or yyyy-mm-dd
select case when substring(StartDate, 3, 1) = '/'
then convert(date, StartDate, 103)
else convert(date, StartDate, 121)
end
SQL Server is actually quite good about figuring out formats for a date conversion with no formatting argument. However, it is going to assume MM/DD/YYYY for the second format and generate an error.
So, you can use try_convert() and coalesce():
select coalesce(try_convert(date, startdate, 103),
convert(date, startdate)
)
Here is a SQL Fiddle.
Then, you should go into your data and fix the column. Here is one method:
update t
set startdate = coalesce(try_convert(date, startdate, 103),
convert(date, startdate)
);
alter table t alter column startdate date;
You can add additional formatting for the result set by turning the date back into a string, using convert().
To get YYYY-MM-DD use SELECT CONVERT(varchar, getdate(), 23)
To get MM/DD/YYYY use SELECT CONVERT(varchar, getdate(), 1)
For detailed explaination try this.
Here's an example that first tries to convert the VARCHAR from a 'yyyy-mm-dd' format to the 'dd/mm/yyyy' format.
If that doesn't work out, then it just assumes it's already in the 'dd/mm/yyyy' format.
And then defaults to the first 10 characters from the string.
declare #TestTable table (StartDate varchar(10), DateFormatUsed varchar(10));
insert into #TestTable (StartDate, DateFormatUsed) values
(convert(varchar(10),GetDate() ,103), 'dd/mm/yyyy')
,(convert(varchar(10),GetDate(), 20), 'yyyy-mm-dd')
;
select t.*,
coalesce(convert(varchar(10), try_convert(date,StartDate,20),103), left(StartDate,10)) as [FormattedDate]
from #TestTable t;
But try_convert is only available since MS SQL Server 2012.
For MS SQL Server 2008 we can use a CASE WHEN with a LIKE to check the format.
declare #TestTable table (StartDate varchar(30), DateFormatUsed varchar(30));
insert into #TestTable (StartDate, DateFormatUsed) values
(convert(varchar(10),GetDate(), 103), 'dd/mm/yyyy')
,(convert(varchar(10),GetDate(), 20), 'yyyy-mm-dd')
,(convert(varchar(19),GetDate(), 20), 'yyyy-mm-dd hh:mi:ss')
;
select t.*,
(case
when StartDate like '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]%'
then convert(varchar(10), convert(date, left(StartDate, 10), 20), 103)
else left(StartDate, 10)
end) as [FormattedDate]
from #TestTable t;

sql server convert datetime failed

I want to convert this time_stamp column (nvarchar50) into datetime column in SQL server. the value of time_stamp is "2018-02-16 13:30:27+09:00".
I don't know which datetime code should I use to convert it. Can you help?
This is what I tried:
select convert(datetime,time_stamp, 110) from table;
select convert(datetime,time_stamp, 120) from table;
It is failing because of the timezone embedded in the string. However, it will work if you remove the timezone using string function such as LEFT.
SELECT CONVERT(DATETIME, LEFT(time_stamp, 19), 110)
FROM tableName
Here's a Demo.
There is timezone offset in your sample date. If we want to ignore timezone offset then we can use below code -
declare #x nvarchar(50) = '2018-02-16 13:30:27+09:00'
select convert(datetime,convert(datetimeoffset, #x))
Declare #dt NVARCHAR(100) = '2018-02-16 13:30:27+09:00'
select CAST(SWITCHOFFSET(TODATETIMEOFFSET( LEFT(#dt , 19) ,RIGHT(#dt, 6)),0) AS DATETIME)
Returns:
2018-02-16 04:30:27.000

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

concatenate two columns with date and time in sql?

I have two columns as orderdate(03/02/2011) and ordertime(10.34 am) in which i have to concatenate these two columns and show it in another column as datetime values(03/02/2011 10:34:16.190)....
any suggestion?
In general, the solution is to add days to the time value which has zero for its day portion. You are not clear as the data types of the two values, however one solution would be:
With Inputs As
(
Select '20110302' As DateVal, '10:34 AM' As TimeVal
)
Select DateAdd(d, DateDiff(d, 0, Cast(DateVal As datetime)), Cast(TimeVal as datetime))
From Inputs
A more explicit version assuming the inputs are strings and given your exact inputs:
Set DateFormat MDY
With Inputs As
(
Select '03/02/2011' As DateVal, '10:34 AM' As TimeVal
)
Select DateAdd(d, DateDiff(d, 0, Cast(DateVal As datetime)), Cast(TimeVal as datetime))
From Inputs
Assuming you are working with a DATE and a TIME, you need to convert before you can add.
SELECT [orderdate] + CONVERT(datetime, [ordertime])
you want in programatically or in sql server:
in Sql Server:
select orderdate + ordertime as 'YourColumnName'
hope this help.
In MySQL, it'll work like this
SELECT Concat(orderdate, " ", ordertime) FROM vendors ORDER BY vend_name;