Convert ISO-8601 varchar (0000-00-00T00:00:00+00:00) to datetime in SQL - 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);

Related

Convert varchar to date without timestamp

I am trying to convert/select the nvarchar datatype to date format (YYYY-MM-DD).
The table contains the date in DD/MM/YYYY format & also the null values.
Below SQL query is working fine but it has timestamp in the output
select Date4 = Convert(datetime, Last_Paid_Date, 103) FROM table
2021-01-30 00:00:00.000
My requirement is to have only the date in (YYYY-MM-DD) format
normally this should work
select Convert(date, Last_Paid_Date, 103) from tablename
But if you get conversion errors you can try this
SELECT convert(date, convert(datetime, Last_Paid_Date, 103)) FROM TableName
if Date cannot be used to convert from your format, the trick is to convert to a datetime first, and then convert that into a date.
Much much better would be to store the data in a column with type Date instead of varchar off course
I find this also some good reading
EDIT
if you keep getting conversion errors, then probably there are invalid dates in your varchar column. That is why you should never never never store dates/time in a varchar column.
To fix this, you could use this
SELECT try_Convert(date, Last_Paid_Date, 103) from tablename
this will put NULL in all columns that have an invalid date/time.
Drawback is that from all the rows that will have a value NULL, you cannot know if the original value was also NULL or an invalid date/time value.
Please try the below.
SELECT Date4 = CONVERT(DATE, Last_Paid_Date, 103) FROM TableName
OR
SELECT Date4 = CAST(GETDATE() AS DATE) FROM TableName
This will remove the Timestamp and give you only the Date values in the (YYYY-MM-DD) format.
You can go for simple conversion.
SELECT Convert(date, '20/01/2020', 103)
2020-01-20
You can go for conversion for the table as given below:
SELECT Convert(date, val, 103) as dateval FROM
(
values
('20/01/2020'),(null)
) as t(val)
dateval
2020-01-20
NULL
The issue with your query is that the column: "Last_Paid_Date" contains NULL String, which needs the conversion as they are characters.
You can try the below query:
SELECT convert(date, REPLACE(Last_Paid_Date,'NULL','01/01/2001'), 103)
, convert(datetime, REPLACE(Last_Paid_Date,'NULL','01/01/2001'), 103)
FROM table
The query will replace the NULL strings with a default value if any and then do the date/datetime conversions accordingly
You can chain two conversions : the first one converts the original dd/mm/yyyy (103) to a datetime value, and the second conversion turns that datetime into a yyyy-mm-dd (120) string.
select Date4 = convert(varchar(10), convert(date, Last_Paid_Date, 103), 120)
from table

How to convert string in 'DD/MM/YYYY' or 'YYYY-MM-DD' into date in SQL Server?

I've got a string here which needs to be converted into date but the problem is that it could either be in 'DD/MM/YYYY' or 'YYYY-MM-DD' format.
I've already tried convert which only works for one of the two formats but not both:
declare #string nvarchar(255) = '2019-05-21'
declare #table table (date date)
insert into #table
select convert(date, #string, 111) as date
select * from #table
declare #string nvarchar(255) = '21/05/2019'
declare #table table (date date)
insert into #table
select convert(date, #string, 103) as date
select * from #table
Both of the above solutions result in an error is I use the other format.
Is there a way to get a string converted to date regardless of what format it is in?
Use try_convert():
insert into #table
select coalesce(try_convert(date, #string, 111),
try_convert(date, #string, 103)
) as date
try_convert() returns NULL if the conversion fails. In that case, the conversion will move on to the next pattern. With coalesce(), you can have as many different formats as you like.
You can use TRY_PARSE or PARSE to parse the date literal using a specific culture.
The second format YYYY-MM-DD is an unambiguous date format for the "new" date types like date and datetime2. It's not affected by the DATEFORMAT setting like datetime.
This means you only need to find one culture that can handle the first format. All of the following queries will return the same value :
select parse('21/05/2019' as date using 'en-GB')
-----
2019-05-21
select parse('2019-05-21' as date using 'en-GB')
-----
2019-05-21
select try_parse('21/05/2019' as date using 'en-GB')
-----
2019-05-21
select try_parse('2019-05-21' as date using 'en-GB')
-----
2019-05-21
If you are on SQL 2012 and above, you can use the FORMAT function.
The signature of this function is - FORMAT (value,format[,culture])
Example: SELECT FORMAT (getdate(), 'dd-MM-yyyy') as date and in your case SELECT FORMAT(CAST(<str_value> as DATE), 'yyyy-mm-dd')

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

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

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