简体   繁体   中英

Datetime acting weird on different computers

I'm trying to make a program that will do some queries on a SQL Server, for some reason the code is having strange behavior, since it will create different date values on 2 of my computers.

This is the part of code behaving weird.

Query += " dbo.MensajesProcesados.SentDateTime BETWEEN CONVERT(VARCHAR, '" + FechaInicio.Value.ToUniversalTime().ToShortDateString() + "', 103) AND CONVERT(VARCHAR, '" + FechaFin.Value.ToUniversalTime().ToShortDateString() + "', 103)";

in 1st computer(working) gives me:

BETWEEN CONVERT(VARCHAR, '5/18/2015', 103) AND CONVERT(VARCHAR, '5/19/2015', 103)

and the second computer which is not working:

BETWEEN CONVERT(VARCHAR, '17/05/2015',103) AND CONVERT(VARCHAR, '19/05/2015',103)

This one is not working and will output me the following error

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

Please, any help would be great!

Provide Sql Server with culture neutral format 'yyyyMMdd' :

Query += " dbo.MensajesProcesados.SentDateTime
BETWEEN '" + FechaInicio.Value.ToString("yyyyMMdd") + "' 
AND '" + FechaFin.Value.ToString("yyyyMMdd") + "'";

This has to do with the culture/language of the SQL Server. See here: SQL Server Datetime issues. American vs. British?

set language us_english
declare @d datetime = '1929/12/18'

You could follow the solution in the question and change the language manually, or you can build the date by inputting the month and year so there's no room for translation, see some of the answers here: Create a date with T-SQL

DECLARE @day int, @month int, @year int
SELECT @day = 4, @month = 3, @year = 2011
SELECT dateadd(mm, (@year - 1900) * 12 + @month - 1 , @day - 1)

Try CONVERT instead of CAST.

CONVERT allows a third parameter indicating the date format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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