how to convert string and datetime value in sql - sql-server

I Have This Type Of Value
fe80::d235:a0ce:c3ce:b764%14:2/17/2023 12:29:34 PM
and I Want this Value As 02/17/2023 Using SQL

try?
DECLARE #TestString VARCHAR(100)
SET #TestString='fe80::d235:a0ce:c3ce:b764%14:2/17/2023 12:29:34 PM'
SELECT REPLACE(LEFT(REVERSE(LEFT(REVERSE(#TestString),LEN(#TestString)-CHARINDEX('/',#TestString)+3)),10),':','')

Here is an example to convert your string into a Date.
SELECT FORMAT(CONVERT(datetime, 'fe80::d235:a0ce:c3ce:b764%14:2/17/2023 12:29:34 PM'), 'MM/dd/yyyy') AS formatted_date;

Related

Convert varchar to DateTime not working on table but works on individual values

I have a table with column ImportDate of datatype varchar(100).
I want to convert its values from varchar to Datetime and for that I have used this query:
select
convert(datetime, ImportDate)
from ImportHistory
But it throws an exception with message
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
But when I individually select each value and run the statement it works fine. For example the below query works perfectly, and so do all the values in the table
select convert(Datetime, '1826-07-04 18:20:00')
There are no null values in that table and below are the values:
1826-07-04 18:20:00
1826-07-04 18:20:00
1917-11-08 11:11:00
2003-07-16 16:02:00
1984-06-08 00:00:00
2004-06-05 00:00:00
1826-07-04 18:20:00
1826-07-04 18:20:00
1917-11-08 11:11:00
2003-07-16 16:02:00
1984-06-08 00:00:00
2004-06-05 00:00:00
If you're using SQL Server 2012+, use TRY_PARSE or TRY_CONVERT in this kind of scenario:
DECLARE #ImportHistory TABLE (ImportDate VARCHAR(100))
INSERT #ImportHistory
VALUES
('1826-07-04 18:20:00'),
('1826-07-04 18:20:00'),
('1917-11-08 11:11:00'),
('2003-07-16 16:02:00'),
('1984-06-08 00:00:00'),
('2004-06-05 00:00:00'),
('1826-07-04 18:20:00'),
('1826-07-04 18:20:00'),
('1917-11-08 11:11:00'),
('Invalid!'),
('2003-07-16 16:02:00'),
('1984-06-08 00:00:00'),
('2004-06-05 00:00:00')
SELECT
ImportDate, TRY_CONVERT(datetime, ImportDate) as dt
FROM #ImportHistory
WHERE TRY_CONVERT(datetime, ImportDate) IS NULL
-- output: Invalid!, NULL
To find the invalid value. If you want invalid values to be converted to NULL, you can remove the WHERE clause and just use TRY_PARSE in place of CONVERT.
The dates you've listed are all valid, but it's very likely in your actual table you have at least one invalid date - or at least not one that can be parsed as is (extra space, month/day stored in different culture format, etc.).
If you must keep your column as a VARCHAR for some unknown reason and you want to make sure that applications don't insert unparsable dates into it, you could add a constraint
ALTER TABLE ImportHistory
ADD CONSTRAINT CK_ImportDate
CHECK(TRY_CONVERT(datetime, ImportDate) IS NOT NULL)
If you don't have SQL Server 2012+, you could try making a cursor to find the invalid data:
DECLARE #dt VARCHAR(100);
DECLARE #dt2 DATETIME;
BEGIN TRY
DECLARE test_cursor1 CURSOR FOR
SELECT Importdate FROM #ImportHistory
OPEN test_cursor1
WHILE ##FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM test_cursor1 INTO #dt
SET #dt2 = CONVERT(datetime, #dt)
END
END TRY
BEGIN CATCH
SELECT #dt
END CATCH
-- output: Invalid!
This resolved the issue.
Select Convert(Datetime, LTRIM ( RTRIM ( REPLACE ( REPLACE ( REPLACE ( ImportDate, CHAR(10), ''), CHAR(13), ''), CHAR(9), '') ) )) from ImportHistory
Thank you All !!

Convert date from dd-mm-yyyy to yyyy-mm-dd in SQL Server

I want to convert given date into the format YYYY-MM-DD.
Given date:
DECLARE #Date1 VARCHAR(50) = '30-01-2015'
Now I want to convert it into the 2015-01-30.
My try:
Try1:
SELECT CONVERT(VARCHAR(50),'30-01-2015',126)
Try2:
SELECT CONVERT(VARCHAR(50),'30-01-2015',120)
For both try the result remain same that is 30-01-2015.
Try this:
DECLARE #Date1 VARCHAR(50) = '30-01-2015'
SELECT CONVERT(VARCHAR(10), CONVERT(date, #Date1, 105), 23)
Try this way
SELECT CONVERT(date,'30-01-2015',103)
Convert date from dd-mm-yyyy hh:mm:ss to yyyy-mm-dd hh:mm:ss in SQL Server
convert(datetime,'18-11-2019 00:00:00',105) // will return 2019-11-18 00:00:00.000

convert nvarchar to smalldatetime in sql server

I have one table in which nvarchar data are there.
Table
18-FEB-11 10.29.52.000000000 AM
20-FEB-11 04.10.40.000000000 PM
23-SEP-10 10.34.57.714000000 AM
08-OCT-10 09.41.16.921000000 PM
I want to convert this field to small date time in sql server 2008 R2
How can i convert it.
Expected OUTPUT:
2011-02-18 10:29:52
2011-02-20 16:10:40
2010-09-23 10:34:57
2010-10-08 21:41:16
Try this please
declare #s_date as nvarchar(100)= '18-FEB-11 10.29.52.000000000 AM'
SELECT CONVERT(nvarchar(100),CAST(REPLACE(REPLACE(#s_date, SUBSTRING(#s_date, 19, 10),''),'.',':') as datetime), 120)
result : 2011-02-18 10:29:52
this should work too:
DECLARE #datestring NVARCHAR(50) = '08-OCT-10 09.41.16.921000000 PM'
SELECT CAST(REPLACE(LEFT(#datestring,18),'.',':') + RIGHT(#datestring,2) AS SMALLDATETIME)

Convert String of datetime(201004301342) into Datetime value(103 Format)

I Have a string like as given below
201004301342
Need to convert it into dd/mm/yy format
Can anyone help me please?
This will change the value to a datetime. A datetime has no format until you convert back to a string again.
You can use stuff to change the string value to 20100430 13:42 and then cast to datetime.
declare #Date varchar(12)
set #Date='201004301342'
select cast(stuff(stuff(#Date, 11, 0, ':'), 9, 0, ' ') as datetime)
if you want a string and start string is always with this format then
declare #date varchar(50)
set #date = '201004301342'
SELECT convert(varchar, cast(substring(#date, 1, 8) as datetime), 103)

How to solve the date comparison issue in SQL Server?

I am using the following way to compare two dates:
if CONVERT(varchar(20), #ScheduleDate, 101) >= CONVERT(varchar(20), #CurrentDateTime, 101)
This is working fine for the current year, but when the comes in yearly like one date is 12/31/2012 and 1/1/2013 then its not working.
Please help me how can I resolve this.
why do you comparing strings?
you can compare dates
if #ScheduleDate >= #CurrentDateTime
but if your date contains time, I usually do
if convert(nvarchar(8), #ScheduleDate, 112) >= convert(nvarchar(8), #CurrentDateTime, 112)
112 datetime format is YYYYMMDD so it's good for compare dates
You have to remember that string comparison is from left to right, so "1/...." is smaller than "12/...".
You need to use DATETIME comparisons, not string comparison.
Something like
DECLARE #ScheduleDate DATETIME = '1/1/2013',
#CurrentDateTime DATETIME = '12/31/2012'
IF (#ScheduleDate >= #CurrentDateTime)
BEGIN
SELECT #ScheduleDate, #CurrentDateTime
END
DECLARE #ScheduleDateString VARCHAR(20) = '1/1/2013',
#CurrentDateTimeString VARCHAR(20) = '12/31/2012'
IF (CONVERT(DATETIME,#ScheduleDateString,101)>=CONVERT(DATETIME,#CurrentDateTimeString,101))
BEGIN
SELECT CONVERT(DATETIME,#ScheduleDateString,101),CONVERT(DATETIME,#CurrentDateTimeString,101)
END
SQL Fiddle DEMO
Note that if the variables are already datetimes, you do not need to convert them.
Assuming that both variables are currently DateTime variables, can't you just compare them without converting to strings?
declare #ScheduleDate DATETIME, #CurrentDateTime DATETIME
SET #ScheduleDate = '1 Jan 2013'
SET #CurrentDateTime = GetDate()
IF (#ScheduleDate >= #CurrentDateTime)
BEGIN
SELECT 'Do Something'
END
ELSE
BEGIN
SELECT 'Do Something Else'
END
when you use CONVERT(nvarchar(8), #ScheduleDate, 112) function it's return string instead of date.
so,
Use "112" DateFormat in Sql Server it's return string in "YMD" format without any sepration.
compare that string in your query and get desire output.
Such as "if CONVERT(nvarchar(8), #ScheduleDate, 112) >= CONVERT(nvarchar(8), #CurrentDateTime, 112)"
I would not use CONVERT to compare formatted strings. It is slow (well, more like microseconds, but still)
I use a UDF for SQL prior to version 2008
CREATE FUNCTION [dbo].[DateOnly] (#Date DateTime)
RETURNS Datetime AS
BEGIN
Return cast (floor (cast (#Date as float)) as DateTime)
END
and for versions >=2008 this approach
select convert(#MyDateTime as DATE)
Of course, you can compare datetime values directly, but to know whether two datetime values are on the same date (ignoring the time component), the above versions have proven to be effectivy.
Date : From and To with following format
from_Date# = #dateformat("#form.from#", "mm/dd/yyyy")
to_Date# = #dateformat("#now()#" + 1, "mm/dd/yyyy")
In SQL Statement
WHERE a.DateCreated >= CAST ('#from_date#' AS DATE) and a.DateCreated <= CAST('#to_date#' AS DATE)
This is working fine without any cast of original date time column

Resources