0

I have inserted a field with a format like this 'Jul 08, 2019 (10:57 AM)'.

now i want to compare dates but this is a string datatype not date, i tried to convert it to date before comparing with date, it fails and gives error i tried Convert function and Cast function

CONVERT(date, 'Jul 08, 2019 (10:57 AM)') Cast('Jul 08, 2019 (10:57 AM)' as date)

is there any way to convert it or to compare it with date like this format 'MM/DD/YYYY'

2
  • CONVERT supports various styles. This particular format isn't one of them, but you can manipulate the string first so it does match one of these formats (e.g. SELECT CONVERT(DATETIME, REPLACE(REPLACE('Jul 08, 2019 (10:57 AM)', '(', ''), ')', ''), 100)). Do try to change these values once and for all so all future queries can simply use DATETIME for comparison; do not keep this conversion around in queries. Commented Feb 13, 2020 at 13:47
  • I knew it was an issue with the parentheses but I didn’t know how to get red of them. Thank you Commented Feb 13, 2020 at 14:44

2 Answers 2

1

Your problem are the parenthesis in time. Remove them like:

select convert(DATETIME,  REPLACE(REPLACE('Jul 08, 2019 (10:57 AM)',')',''),'(',''))    
Sign up to request clarification or add additional context in comments.

Comments

1

The parens are throwing off the conversion.

SELECT 
FORMAT(CONVERT(date, REPLACE(REPLACE('Jul 08, 2019 (10:57) AM', '(', ''), ')', '')), 'MM/dd/yyyy')
,FORMAT(Cast(REPLACE(REPLACE('Jul 08, 2019 (10:57) AM', '(', ''), ')', '') as date), 'MM/dd/yyyy')
,CONVERT(date, REPLACE(REPLACE('Jul 08, 2019 (10:57) AM', '(', ''), ')', ''))
,Cast(REPLACE(REPLACE('Jul 08, 2019 (10:57) AM', '(', ''), ')', '') as date)

If you need the MM/DD/YYYY format the first two options will work. If you just need the date value for a comparison you can replace the parens.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.