sql server convert datetime failed - sql

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

Related

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

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;

Concatenate date and string to create datetime in SQL

I need to concatenate a datetime and a time field in SQL to a single date time.
e.g I have a datetime of 2017-09-05 00:00:00.000 and a string time of 11:00. What I want is a single field in a view of 2017-09-05 11:00:00.000
I have tried casting the datetime to a date and then concatenate the new date and string date field together but this doesn't work.
To cast the datetime I am using: CAST(dtDate AS DATE) AS dtNewDate which works fine. When I then use: CAST(dtNewDate + szTime AS datetime) AS dtNewDateTime the creation of the view works fine but selecting the top 1000 returns a "conversion failed when converting date and/or time from character string."
Is there an easier way to do this or can anyone offer some advise (other than storing the date and time in a single datetime field in the first place as it is populated by a third party application which I do not have access to change)
You can add two datetime values together, so try:
CAST(dtDate AS DATETIME) + CAST(CAST(szTime AS TIME) as DATETIME)
Assuming 11:00 stands for 11:00:00, you can do something like this:
SELECT dtDate + CONVERT(DateTime, szTime, 108)
FROM...
See a live demo on rextester
You can try following.
DECLARE #YourDate AS DATETIME
SET #YourDate = CONVERT(VARCHAR(10), '2017-09-05 00:00:00.000', 111) + ' 11:00'
PRINT #YourDate
another way is to get the hour from your stringfield, convert it to int, and add that as hours to the datetime
declare #date datetime = '20170905'
declare #stringtime varchar(5) = '11:00'
select left(#stringtime, 2),
dateadd(hour, convert(int, left(#stringtime, 2)), #date)
If you also need the minutes you can do it like this :
declare #date datetime = '20170905'
declare #stringtime varchar(5) = '11:05'
select left(#stringtime, 2),
right(#stringtime, 2),
dateadd(minute, convert(int, right(#stringtime, 2)), dateadd(hour, convert(int, left(#stringtime, 2)), #date))
This will only work if the stringfield is always in format hh:mm
If you care about precision with DATETIME2,
DECLARE #D DATETIME = '2017-01-01';
DECLARE #T varchar(7) = '11:00';
SELECT DATEADD(day, DATEDIFF(day, '19000101', #D), CAST(CAST(#T AS TIME) AS DATETIME2(7)));
Running example here

How to convert a timestamp (DATE FORMAT) to BIGINT in SQL

I need to convert the timestamp value (Format: 2012-11-19 14:29:50.0) to a BIGINT value (Format: 2012111315041650 = YYYYMMDDhhmmss). I need to insert current time in a column of a table which accepts only BIGINT.
I am using Squirrel SQL Client Version 3.3.0. The query I am using right now is
INSERT INTO table1 (BINGINT_DATE, TIMESTAMP_DATE)
VALUES (2012111315041650, CURRENT_TIMESTAMP);
Instead of manually entering the BIGINT_DATE value, I want to convert the CURRENT_TIMESTAMP or NOW() to a BIGINT value as the format YYYYMMDDHHMISS
Something like
INSERT INTO table1 (BINGINT_DATE, TIMESTAMP_DATE)
VALUES ("CONVERT(CURRENT_TIMESTAMP,BIGINT)", CURRENT_TIMESTAMP);
Let me know if it is feasible to do this way
Please help me with this.
Thanks
For Postgres you can use:
INSERT INTO table1 (BINGINT_DATE, TIMESTAMP_DATE)
VALUES (to_char(current_timestamp, 'yyyymmddhh24miss')::bigint, CURRENT_TIMESTAMP);
To convert timestamp values to bigint values (in seconds) you can do it in this way:
SELECT (EXTRACT(EPOCH FROM TIMESTAMP '2019-04-02T14:56:39.009'))::bigint -- -> 1554216999
To convert timestamp values to bigint values (in millis) you can do it in this way:
SELECT ((EXTRACT(EPOCH FROM TIMESTAMP '2019-04-02T14:56:39.009'))::numeric * 1000)::bigint -- -> 1554216999009
If you want to convert all timestamp values of a column into a table into another column of the same table you can run this query (result in millis):
UPDATE $table_name$ SET $column_with_values_bigint$ = (EXTRACT(EPOCH FROM $column_with_values_timestamp$)::numeric * 1000)::bigint
Hope this help.
For Oracle: Use to_char and to_number functions as below
TO_NUMBER(TO_CHAR('2012-11-19 14:29:50.0', 'YYYYMMDDHHMISS'))
For MySQL: Use DATE_FORMAT & CONVERT as below:
CONVERT(DATE_FORMAT('2012-11-19 14:29:50.0'', '%Y%M%d%H%i%s'), UNSIGNED BIGINT)
The following will give you what (I think) you are after:
DECLARE #TM VARCHAR(50) = '2012-11-19 14:29:50.0'
SELECT (CAST(SUBSTRING(#TM,1,4) AS INT) * 10000000000)
+ (CAST(SUBSTRING(#TM,6,2) AS INT) * 100000000)
+ (CAST(SUBSTRING(#TM,9,2) AS INT) * 1000000)
+ (CAST(SUBSTRING(#TM,12,2) AS INT)* 10000)
+ (CAST(SUBSTRING(#TM,15,2) AS INT)* 100)
+ (CAST(SUBSTRING(#TM,18,2) AS INT))
However there may be a better solution to the overall problem which others have mentioned, if you give some more details we might be able to suggest a less dirty alternative.
you can try something like that on MS SQL:
From bigint to datetime:
select dateadd(s, convert(bigint, '<bigint value like 1477958400000>') / 1000, convert(datetime, '1-1-1970 00:00:00'))
From datetime to bigint:
select cast(datediff(s, convert(datetime, '1-1-1970 00:00:00'), convert(datetime, '<datetime value like 11-01-2016>')) as bigint)* 1000
Cheers
DATETIME to BIGINT;
SELECT CONVERT(BIGINT, FORMAT(CURRENT_TIMESTAMP, 'yyyyMMddHHmmss'))
OR
SELECT CONVERT(BIGINT, FORMAT(GETDATE(), 'yyyyMMddHHmmss'))
BIGINT to DATETIME;
SELECT CONVERT(DATETIME, FORMAT(20191220213340, '####-##-## ##:##:##'))
Sql Server; Replace GETDATE() With your Column name
SELECT CONVERT(bigint,
CONVERT(VARCHAR(12) , GETDATE() ,112) +
REPLACE(CONVERT(VARCHAR(8) , GETDATE() ,108),':',''))