5

I am facing a problem

Error converting data type nvarchar to datetime

during inserting a date as a string literal in the format of 26/01/2017. I am using this code in SQL Server during insert:

CONVERT(DATETIME, @PaymentDate, 104)
3

7 Answers 7

3

Try CONVERT(DATETIME, @PaymentDate, 103)

104 is the German style which uses periods between the numerals, as opposed to slashes. 103 is the British/French style.

See: https://msdn.microsoft.com/en-us/library/ms187928.aspx

Sign up to request clarification or add additional context in comments.

Comments

3

I've noticed your question is also tagged with .
If you are passing the date from c# to sql server, Don't pass dates as strings. Pass them as DateTime.
The .Net DateTime maps directly to SQL Server's DateTime.
This way, you will not have to deal with the display format at all, since both c# and SQL Server does not store display format in DateTime.

If you really need to convert the string '26/01/2017' to date, you should use 103 for your style argument, as already suggested in other answer.

Comments

1

This Example runs without any problem:

Declare  @PaymentDate  nvarchar(40)
set @PaymentDate = '26/01/2017'
SELECT CONVERT(DATETIME,@PaymentDate,104)

Result:

2017-01-26 00:00:00.000

Comments

0

check the dateformat in sqlserver and then convert accordingly. code for dateformat
SET DATEFORMAT mdy

Comments

0

Try these code, and make sure date value is not null and past 1970-1-1。

CONVERT(DATETIME,@PaymentDate,103)

Or

CONVERT(DATETIME,@PaymentDate,105)

Comments

0

use SelectedDate incase you are saving your data and get that error ie. cmd.Parameters.AddWithValue("EndDate", EndDatep.DateInput.SelectedDate);

Comments

0

The issue I faced was that the date was having the correct format but the time part was incorrect, the date was like

07/28/2021 00:00 PM

where 00 hours cannot be possible in PM, that is why DB was not accepting them while saving the date/time. so I converted the date to

07/28/2021 00:00 AM

and it was saved. maybe helpful for anyone.

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.