Parameter Date Conversion - visual-studio

am using C#, VS 2005 and SQL 2000
I have date conversion problem my SQL table having field as below
Fields:
datefrom
dateto
My SQL query in C# is
string sql = "insert into companymast (cname, datefrom, dateto) values(#cname, #datefrom, #dateto)";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#cname",SqlDbType.Varchar(50)).Values = cname.text;
cmd.Parameters.Add("#datefrom",SqlDbType.Datetime).Values = maskedTextBox1.text;
cmd.Parameters.Add("#dateto",SqlDbType.Datetime).Values = maskedTextBox2.text;
cmd.ExecuteNonQuery();
But the above throw Error Like date non conversion string to date
I have to put date in dd/MM/yyyy format code, 103
so how do i do?
Help me out, please.

maskedBox1.text is a string. You're assigning that to a SqlParameter's data member, and it tries to convert whatever it receives to the data type you request.
A more solid solution would be to convert to DateTime explicitly, and pass the converted value to the SqlParameter. This way, you have more control over the conversion, and you'll see exactly where and why it goes wrong when it does. Example:
DateTime fromDate = DateTime.Parse(maskedTextBox1.text);
cmd.Parameters.Add("#datefrom",SqlDbType.Datetime).Values= fromDate;
For DateTime.Parse, see: http://msdn.microsoft.com/en-us/library/1k1skd40.aspx

Related

How to use UK-format date in linq with operators

i have got a big problem with converting dates in c#,i want to query using LINQ,in my condition i have to put date,if i put DateTime its in american format and database which expecting UK format does not recognize the date,if use ToString('dd,MM,yyyy') to get british format,i cant use string in LINQ condition,what should i do?
var rslt=(from t in cr.table1
join v in cr.errorCatGroup
on t.m_error_id equals v.m_error_id
where t.m_date >= myDateTime1 && t.m_date <= myDateTime2
select new {
GroupName=t.Error
}).ToList();
i get mDateTime1 and myDateTime2 like :
CultureInfo ukCulture = new CultureInfo("en-GB");
DateTime myDateTime1 = DateTime.Parse("30/09/2018", ukCulture.DateTimeFormat);
DateTime result12 = DateTime.ParseExact("01-10-2018", "d-M-yyyy", CultureInfo.CurrentCulture);
so whats the right way of using it in LINQ

LINQ - To Get Year from Date which is of Type String

I have this LINQ query:
hdms = from t in db.HOLIDAY
join t1 in db.EMPLOYEE on t.UPDATED_BY equals t1.EMP_CODE
where
t.HOLIDAY_NAME == searchtext &&
t.DOH.Value.Year == 2016
orderby
t.DOH
select new HOLIDAYDETAILS
{
HOLIDAY_NAME = t.HOLIDAY_NAME,
DOH = t.DOH,
EMP_NAME = t1.EMP_NAME
};
While executing this, below error occurs:
'string' does not contain a definition for 'Value' and no extension method 'Value' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
Error comes under Value in t.DOH.Value.Year = 2016.
Here type of t.DOH is string and value is 2016-04-14
I have also tried this one:
hdms = from t in db.HOLIDAY
where
DateTime.ParseExact(t.DOH, "yyyy-MM-dd", CultureInfo.InvariantCulture).Year == DateTime.Now.Year
orderby
t.DOH
select new HOLIDAYDETAILS
{
DOH = t.DOH
};
Now got this error:
LINQ to Entities does not recognize the method 'System.DateTime ParseExact(System.String, System.String, System.IFormatProvider)' method, and this method cannot be translated into a store expression.
Is there any other way to convert string to date type in LINQ?
Since DOH is of type string you could use StartsWith to check if the string starts with 2016.
where
t.HOLIDAY_NAME == searchtext &&
t.DOH.StartsWith("2016")
A better option would be to change your datatype of DOH to DateTime/DatetTime?, to get better support when working with date and time values. Then you can leave your query as it is.
You can parse DateTime from string like:
DateTime.ParseExact(t.DOH, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Then you can get year value using [DateTimeVariable].Year

Assigning a DateTime to a Date database column

I have error:
Cannot implicitly convert type 'string' to 'System.DateTime'a
When I want get a DateTime
var dat = DateTime.Now.ToShortDateString();
godz.date = dat;
godz.data is type Date in database.
How fix it?
That's because you are trying to pass a string where a datetime is expected. Try changing to this:
var dat = DateTime.Now;
How about setting
godz.date = DateTime.Now;

Why can't I cast nullable DateTime as string in a LinQ query?

I am trying to take a DateTime value, and if it is not null return the Short Time String. My query looks like this:
(TimeIn is NOT NULLABLE, whereas TimeOut is NULLABLE)
var times = from t in db.TimePostings
where t.MemberID == member.MemberID
select new
{
Date = t.TimeIn.ToShortDateString(),
TimeIn = t.TimeIn.ToShortTimeString(),
TimeOut = t.TimeOut.HasValue ? t.TimeOut.Value.ToShortTimeString() : "-------"
};
gvTimePostings.DataSource = times;
gvTimePostings.DataBind();
but this fails when I try to databind with the error:
Could not translate expression 'Table(TimePosting).Where(t =>
(t.MemberID == Invoke(value(System.Func1[System.String])))).Select(t
=> new <>f__AnonymousType84(Date = t.TimeIn.ToShortDateString(), TimeIn = t.TimeIn.ToShortTimeString(), TimeOut =
IIF(t.TimeOut.HasValue, (t.TimeOut ??
Invoke(value(System.Func`1[System.DateTime]))).ToShortTimeString(),
"-------"), Hours = ""))' into SQL and could not treat it as a local
expression.
I also get a similar error if I try to use:
TimeOut = t.TimeOut.HasValue ? Convert.ToDateTime(t.TimeOut).ToShortTimeString() : "-------"
however, if I change the TimeOut property to:
TimeOut = t.TimeOut.HasValue ? t.TimeOut.ToString() : "-------",
it works fine, but does not format the time like I want it (shortTimeString).
what's up with that?
As others have said, the problem is with trying to convert ToShortDateString etc to SQL. Fortunately, this is easy to fix: fetch the data with SQL, then format it in .NET:
var timesFromDb = from t in db.TimePostings
where t.MemberID == member.MemberID
select new { t.TimeIn, t.TimeOut };
var times = from t in timesFromDb.AsEnumerable()
select new
{
Date = t.TimeIn.ToShortDateString(),
TimeIn = t.TimeIn.ToShortTimeString(),
TimeOut = t.TimeOut.HasValue
? t.TimeOut.Value.ToShortTimeString()
: "-------"
};
The call to AsEnumerable() here basically means, "stop trying to process the query using SQL; do the rest in LINQ to Objects".
ToShortTimeString() has no translation in SQL. Because of that, converting the statement into a single SQL statement fails and the exception is thrown.
If you break the statement into two calls (one to retrieve the data and another to create the projection), things will work just fine:
// must call ToList to force execution of the query before projecting
var results = from t in db.TimePostings
where t.MemberID == member.MemberID
select new { t.TimeIn, t.TimeOut };
var times = from t in results.AsEnumerable()
select new
{
Date = t.TimeIn.ToShortDateString(),
TimeIn = t.TimeIn.ToShortTimeString(),
TimeOut = t.TimeOut.HasValue ?
t.TimeOut.Value.ToShortTimeString() :
"-------"
};
Have you tried:
TimeOut = t.TimeOut.HasValue ? t.TimeOut.ToString("d") : "-------",
This will normally give the short format of the DateTime. Whether it works or not will depend on whether it can be translated to SQL or not.
If it doesn't work you'll have to break the query into two parts. The first gets the data, the second format it. You'll have to convert the first query to a list (.ToList()) to force the SQL to be evaluated.
Simply, it's not supported by this specific linq provider.
Your linq query is converted into an expression tree. It is up to the SQL Linq provider to convert this expression tree into SQL. Understandably, it does not have the capability to translate every single .NET function.
Your solution is to explicitly run the SQL by calling ToArray or ToList, and then allow LinqToObjects to handle the rest.
var times = from t in db.TimePostings
where t.MemberID == member.MemberID
select new {
TimeIn = t.TimeIn,
TimeOut = t.TimeOut
};
var timesFormated = times.ToArray() // Runs the query - any further processing will be run in memory by the local .NET code
.Select(t => new {
Date = t.TimeIn.ToShortDateString(),
TimeIn = t.TimeIn.ToShortTimeString(),
TimeOut = t.TimeOut.HasValue ? t.TimeOut.Value.ToShortTimeString() : "-------",
Hours = ""
}
);
Your query is transformed by LINQ to an SQL that is fired against your database, and there is obviously no way to translate t.TimeOut.Value.ToShortTimeString() to SQL.
Possible solutions are:
First fetch your data from database (by calling .ToList() or .ToArray() on your LINQ query), that converts your IQueryable<> into IEnumerable<> and then apply your transformation for every row fetched.
Use a view that takes the original table and performs the conversion using CONVERT() function on the SQL Server and use it as the source for your Linq-to-SQL class. That would be performanter, but requires some server-side changes.
I had the same problem in a project in vb.net.
The solution I've found is based on the use of:
if(table.field.hasvalue, table.field.value.ToShortDateString, string.format("NULL"))
In this case, if the selected field (table.field) has a value this is converted into a date string otherwise if the field hasn't a value the output field is filled with string "NULL"

Java Oracle date

String sql="select id from period where '"+systemDate+"' between startDate and endDate";
I need to execute this query and I am using oracle 10g. I want to get the id which falls between these dates. Problem I am facing is in oracle my date format is"dd-mon-yy" and systemDate is in format yyyy-mm-dd.So is ther any way to convert java date to dd-mon-format or any other way to execute the above query...
Kindly help.
You should convert your java.util.Date to a java.sql.Date and use a PreparedStatement as shown below:
java.util.Date jStartDate = ...; //your "java" date object
java.sql.Date startDate = new java.sql.Date(jStartDate.getTime());
java.util.Date jEndDate = ...;
java.sql.Date endDate = new java.sql.Date(jEndDate.getTime());
PreparedStatement p = connection.prepareStatement("select id from period where systemDate between ? and ?");
p.setDate(1, startDate);
p.setDate(2, endDate);
ResultSet rs = p.executeQuery();
Java has date formatting classes. DateFormat is the abstract parent class for these, SimpleDateFormat here is probably the one you want
SimpleDateFormat oracleStyle = new SimpleDateFormat("dd-MM-yy");
String dString = oracleStyle.format(systemDate);
String sql="select id from period where '"+systemDate+"' between startDate and endDate";
I havent tested this. The format call might need new string buffers as arguments, and my format string could be off, but this is the idea. Read the documentation

Resources