简体   繁体   English

将数据类型 nvarchar 转换为日期时间 SQL Server 时出错

[英]Error converting data type nvarchar to datetime SQL Server

I am facing a problem我面临一个问题

Error converting data type nvarchar to datetime将数据类型 nvarchar 转换为日期时间时出错

during inserting a date as a string literal in the format of 26/01/2017 .在以26/01/2017格式插入日期作为字符串文字26/01/2017 I am using this code in SQL Server during insert:我在插入期间在 SQL Server 中使用此代码:

CONVERT(DATETIME, @PaymentDate, 104)

Try CONVERT(DATETIME, @PaymentDate, 103) 尝试CONVERT(DATETIME, @PaymentDate, 103)

104 is the German style which uses periods between the numerals, as opposed to slashes. 104是德国风格,它使用数字之间的句点,而不是斜杠。 103 is the British/French style. 103是英国/法国风格。

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

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. 如果要将日期从c#传递给sql server,请不要将日期作为字符串传递。 Pass them as DateTime. 将它们作为DateTime传递。
The .Net DateTime maps directly to SQL Server's DateTime . .Net DateTime 直接映射到SQL Server的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 . 这样,您根本不必处理显示格式,因为c#和SQL Server都不会在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. 如果你真的需要将字符串'26/01/2017'转换为日期,你应该使用103作为你的样式参数,正如其他答案中已经建议的那样。

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

check the dateformat in sqlserver and then convert accordingly. 检查sqlserver中的dateformat然后相应地转换。 code for dateformat dateformat的代码
SET DATEFORMAT mdy 设置DATEFORMAT mdy

Try these code, and make sure date value is not null and past 1970-1-1。 尝试这些代码,并确保日期值不为空并且过去1970-1-1。

CONVERT(DATETIME,@PaymentDate,103)

Or 要么

CONVERT(DATETIME,@PaymentDate,105)

use SelectedDate incase you are saving your data and get that error ie. 如果您正在保存数据并获得该错误,请使用SelectedDate,即。 cmd.Parameters.AddWithValue("EndDate", EndDatep.DateInput.SelectedDate); cmd.Parameters.AddWithValue(“EndDate”,EndDatep.DateInput.SelectedDate);

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 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.在 PM 中不可能有 00 小时,这就是为什么 DB 在保存日期/时间时不接受它们的原因。 so I converted the date to所以我将日期转换为

07/28/2021 00:00 AM 07/28/2021 00:00 AM

and it was saved.它被保存了。 maybe helpful for anyone.也许对任何人都有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM