When i have a leap year in my database (ex.: 29th Feb 2012). The EntityFunctions.CreateDateTime functions throws System.Data.SqlClient.SqlException: Conversion failed when converting date and/or time from character string.
My Code is as follows in my asp.net mvc (C#) application:
from u in _entities.tt_Users
let _start_date = u.Start_Date
let _startDate = _start_date.Day
let _startmonth = _start_date.Month
let _startyear = _start_date.Year
let _starthour = u.Start_Time.Value.Hours
let _startminutes = u.Start_Time.Value.Minutes
let _startseconds = u.Start_Time.Value.Seconds
let _startDateWithTime = EntityFunctions.CreateDateTime(_startyear, _startmonth, _startDate, _starthour, _startminutes, _startseconds)
let _startDateWithZeroTime = EntityFunctions.CreateDateTime(_startyear, _startmonth, _startDate, 0, 0, 0)
let _start_datetime = u.Is_Include_Time ? _startDateWithZeroTime : _startDateWithTime
let _end_date = u.End_Date
let _endDate = _end_date.Day
let _endmonth = _end_date.Month
let _endyear = _end_date.Year
let _endhour = u.End_Time.Value.Hours
let _endminutes = u.End_Time.Value.Minutes
let _endseconds = u.End_Time.Value.Seconds
let _endDateWithTime = EntityFunctions.CreateDateTime(_endyear, _endmonth, _endDate, _endhour, _endminutes, _endseconds)
let _endDateWithZeroTime = EntityFunctions.CreateDateTime(_endyear, _endmonth, _endDate, 0, 0, 0)
let _end_datetime = u.Is_Include_Time ? _endDateWithZeroTime : _endDateWithTime
let _cur_Start_date = u.Is_Include_Time ? _userStartDate : _gMTStartDate
let _cur_End_date = u.Is_Include_Time ? _userEndDate : _gMTEndDate
where u.User_Id == 1 && !u.Is_Deleted
&& _start_datetime >= _cur_Start_date && _end_datetime <= _cur_End_date
select new
{
u.User_id,
u.User_Name,
u.Login_Name,
u.Email_Address
};
Here _userStartDate, _userEndDate, _gMTStartDate and _gMTEndDate are parameters from my function.
If the column "Is_Include_Time" is true, then i have to include TimeSpan also from the table. But for the leap year Its throwing the error.
Any suggestions?
I just encountered the same problem. I have some values in database rows that i need to convert to a datetime. I found out that I can use the following construct:
DateTime startDate = new DateTime(1, 1, 1);
var counters = from counter in entities.Counter
let date = SqlFunctions.DateAdd("day", counter.DayOfMonth-1, SqlFunctions.DateAdd("month", counter.Month-1, SqlFunctions.DateAdd("year", counter.Year-1, startDate)))
where date >= dateFrom && date <= dateTo
orderby date
select new
{
Value = counter.CounterValue,
Date = date
};
I'm not sure of the performance impact, but it does work.
Best regards, Tor-Odd
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With