I have data stored in a SQL database that I'm attempting to read into an ASP.NET MVC application. I can get the data just fine - but the datetimes are not translating into anything useful.
Here's what I have so far (some data redacted as "..."):
public JsonResult GetXYZByStatusJson()
{
var sqlConn = new SqlConnection(...);
var command = new SqlCommand("...", sqlConn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#status", 0);
sqlConn.Open();
var sqlResult = command.ExecuteReader();
var collection = new Collection<Object>();
while (sqlResult.Read())
{
collection.Add(new XYZ(
...
Convert.ToDateTime(sqlResult["DateSent"]),
Convert.ToDateTime(sqlResult["DateDue"]),
...
));
}
sqlResult.Close();
sqlConn.Close();
return Json(collection);
}
The resulting JSON is formatted fine, but the dates look like "\/Date(1294120800000)\/"
How do I properly cast the SQL datetime into a C# DateTime? Using .ToString() doesn't have any affect.
There are nothing wrong with the conversion between Sql Server and C#.
The problem is how JsonResult formats the string.
The following SO question shows how you can process it at client side: How do I format a Microsoft JSON date?
The other way is to create your own alternative to JsonResult
If it is SQL Server, sqlResult["DateSent"].ToString() will give you something like this:
"6/9/1999 12:00:00 AM, 8/15/1999 12:00:00 AM"
Use the built-in string methods (.IndexOf(), .Remove(), etc), or create your own, to parse whatever you need out of this string.
Related
con.open();
SqlCommamd comm = new SqlCommand("Insert into Debt_Tab values('"+Textbox1.text+"')",con);
comm.ExecuteNonQuery();
Textbox1 I is declared as a DateTime in my Sql table.
use this hope this will work
DateTime.ParseExact(Textbox1.text, "MM/dd/yyyy", CultureInfo.InvariantCulture)
There are a lot of different ways to format a date. To be sure that the database gets the correct format I suggest that you parse the date by specifying a culture.
For desktop applications, this is easy since the OS is configured for a specific format, while for web applications the user uses their own preferred format (unless you have specified something else).
To parse using the OS culture:
var date = DateTime.Parse(Textbox1.Text)
To parse using a specific culture:
var swedish = new CultureInfo("sv_se");
var date = DateTime.Parse(TextBox1.Text, swedish);
Another thing. There is something seriously wrong with your code. It's vulnerable to SQL injection attacks. You need to use a parameterized query instead.
var cmd = new SqlCommand(con);
cmd.CommandText = "Insert into Debt_Tab values(#date)";
cmd.Parameters.AddWithValue("date", date);
cmd.ExecuteNonQuery();
Try this:-
Convert.ToDateTime()
example:-
con.open();
SqlCommamd comm = new SqlCommand("Insert into Debt_Tab values('"+ Convert.ToDateTime(Textbox1.text).ToString("mm/dd/yyyy") +"')",con);
comm.ExecuteNonQuery();
Try the following way to validate the date
bool res;
DateTime Date;
string myDate = Textbox1.text;
res = DateTime.TryParse(myDate, out Date);
if(res)
{
// Validation or conversion success and result will be available in Date variable
}
else
{
// conversion Fail
}
I'm relatively new to C#, SQL Server, and Stackoverflow.
I want the format of my date to stay the same from SQL Server to my C# code.
I have a screenshot of the SQL Server table:
.
I just want the format to stay the same. I want the format to stay yyyy-mm-dd instead when I retrieve the data the format is dd/mm/yyyy 0:00:00.
I then use the following code to retrieve the data from the server:
ArrayList a = new ArrayList();
DataTable d = new DataTable();
string sql = "SELECT * FROM myServer";
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(sql, conn);
MySqlDataAdapter myA = new MySqlDataAdapter(cmd);
myA.Fill(d);
cmd.ExecuteNonQuery();
foreach (DataRow row in d.Rows)
{
FitnessManager f = new FitnessManager();
f.testDate = row["testDate"].ToString();
f.tDate = row["tDate"].ToString();
f.dtDate = row["dtDate"].ToString();
a.Add(f);
}
return a;
I would expect the results in the ArrayList to be 2020-10-13, instead I'm getting 10/11/2020 0:00:00.
I do not know why this happens for how to fix this.
You would do something like this:
f.tDate = row["tDate"].ToString("yyyy-MM-dd")
The ToString() function accepts a format string, so you can pretty much convert it to whatever format you want.
More information here:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
I found a previous post that helped me out a lot.
Change date format in C# when reading from database and setting to label
I needed to specify that the data being formatted was datatime rather than ToString() being called as an object.
Thanks E.J for putting me on the right track.
In my app, I am trying to grab a date from the database and compare it against local time. Right now I am getting an error when I am converting to date incorrectly.
I have tried:
Convert.ToDateTime()
DateTime.ParseExact()
My code:
string time = "Select top(1) DATE from SERVICE order by DATE desc";
SqlCommand command = new SqlCommand(time, connection);
connection.Open();
using (SqlDataReader timereader = timecommand.ExecuteReader())
{
while (timereader.Read())
{
if (DateTime.ParseExact(time, "yyyy-MM-dd HH:mm:ss", null).AddMinutes(10) > currenttime)
{
// code
}
}
connection.Close();
}
I am hoping when I retrieve this value from the database, I can convert it into a proper datetime value and compare against local time and run other code after that.
At the moment I am just getting this error:
The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.
I'm probably just dumb and missing something obvious..
Your query selects a single value. Use ExecuteScalar and cast it to a DateTime (it's already a DateTime, but boxed inside an object):
string time = "Select top(1) DATE from SERVICE order by DATE desc";
SqlCommand command = new SqlCommand(time, connection);
connection.Open();
DateTime d = (DateTime)command.ExecuteScalar();
connection.Close();
After you do this, and before you embark on some long mission of this protracted way of getting data out of a database, converting it to objects for use in your app etc, take a look at least at an ORM called Dapper, if not Entity Framework. Dapper's basically what you're doing now, but it auto converts your queries to objects and back and saves a lot of tedious code. With Dapper it'd look more like:
using (var connection = new SqlConnection("connstr"))
{
var d = connection.QuerySingle<DateTime>("SELECT TOP 1 Date FROM ...");
}
Yes, it's not much of a saving over what you have now, right? But what if you have a list of Order that themselves have 20 properties:
using (var connection = new SqlConnection("connstr"))
{
var orders = connection.Query<Order>("SELECT * FROM order WHERE customerID = #custid", new {custid = 123}).ToList();
}
Orders is now a list of Order objects for customer 123, parameterized, injection safe, quick and a one liner to read and populate your orders; doing that in a datareader is going to take at least 25 lines of boring code
http://dapper-tutorial.net and spend 2 minutes reading; I'll lay bets you'll be glad you did
Just try to read the value as a proper, native DateTime type like this (assuming that the DATE column in SQL Server is in fact a DATETIME or similar datatype - not a string - hopefully!):
using (SqlDataReader timereader = timecommand.ExecuteReader())
{
while (timereader.Read())
{
// just read the DateTime value as such
DateTime dt = timereader.GetDateTime(0);
// then do whatever you need to do with this DateTime value .....
}
connection.Close();
}
I have a SQL query that I am passing a C# variable into my Oracle DB.
I am having trouble passing a C# datetime variable, "PROCESS_DATE", into my query in my application. I do not get any records back. If I copy the query into my oracle developer tool, TOAD, it works fine and I get multiple records.
Here is the query I am using in my application:
String SelectAllSQL = "SELECT * FROM REALMS_AUDIT.R2_GROUP_QUERY_RPT WHERE PROCESS_DATE = :pPROCESS_DATE";
I also tried converting the datetime variable into a shortDateString() so it matches the database exactly I then used the TO_DATE function, which I have to use if I query dates directly in TOAD, without any luck. The shortDateString() changes my date into: 1/16/2016, which is what I need, but the OracleDataReader does not like it. Here it the query with the TO_DATE function:
String SelectAllSQL = "SELECT * FROM REALMS_AUDIT.R2_GROUP_QUERY_RPT WHERE PROCESS_DATE = TO_DATE(:pPROCESS_DATE, 'MM-DD-YYYY'";
:pROCESS_DATE is a datetime variable that is passed in.
There must be a breakdown between C# and Oracle in relation to handling a datetime variable. I am using Oracle DataReader to handle the processing of the query.
OracleDataReader dataReader = mDataAccess.SelectSqlRows ( oracleConnection, oracleCommand, sqlCommand, parameters );
while ( dataReader.Read ( ) )
{
groupEntityFacilityRptList.Add ( ReadRecord ( dataReader ) );
}
If I use the TO_DATE function, the application will not step into the while loop. If I use the original query, it does but returns no data.
The datetime variable PROCESSDATE looks like this:
1/16/2016 12:00:00 AM
I notice it has a timestamp on it, so I'm not sure if that is the problem or not.
The data in Oracle is like this:
1/16/2016
Unless I've totally misunderstood your issue, I think you might be making this harder than it needs to be. ODP.net handles all of that dirty work for you. If PROCESS_DATE is an actual DATE datatype in Oracle, then you just need to pass an actual C# DateTime variable to it and let ODP.net do the heavy lifting. There is no need to do conversion of any type, provided you are passing an actual date:
DateTime testDate = new DateTime(2015, 7, 16);
OracleCommand cmd = new OracleCommand(
"SELECT * FROM REALMS_AUDIT.R2_GROUP_QUERY_RPT WHERE PROCESS_DATE = :pPROCESS_DATE",
conn);
cmd.Parameters.Add(new OracleParameter("pPROCESS_DATE", OracleDbType.Date));
cmd.Parameters[0].Value = testDate;
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
object o = reader.IsDBNull(0) ? null : reader.GetValue(0);
}
reader.Close();
If your data in C# is not a date, I'd recommend making it one before even trying:
DateTime testDate;
if (DateTime.TryParse(testDateString, out testDate))
{
// run your query
}
As per my comment, please try below and see this resolves.
TRUNC(TO_DATE(:pPROCESS_DATE,'MM-DD-YYYY HH:MI:SS AM')) if pROCESS_DATE format is 1/16/2016 12:00:00 AM.
TRUNC(TO_DATE(:pPROCESS_DATE,'DD-MM-YYYY HH:MI:SS AM')) if pROCESS_DATE format is 16/1/2016 12:00:00 AM.
First, I learned that my code will not go into the code below unless I actually have records returned to me.
OracleDataReader dataReader = mDataAccess.SelectSqlRows ( oracleConnection, oracleCommand, sqlCommand, parameters );
while ( dataReader.Read ( ) )
{
groupEntityFacilityRptList.Add ( ReadRecord ( dataReader ) );
}
Second, to get ProcessDate to work, I needed to take the string that was coming from my View, convert it to a datetime, and then I formatted it back as a string. It may not be best practices but it worked.
public JsonResult GetGroupReportData ( String reportDate )
{
DateTime processDate = DateTime.Parse ( reportDate );
var monthlyReport = SelectAllGroupRprt (processDate.ToString("MM/dd/yyyy");
return new JsonResult ( )
{
Data = monthly,
MaxJsonLength = Int32.MaxValue
};
}
string sqlUserName3 = "SELECT out_date FROM status where s_id='" + TextBox2.Text + "'";
SqlCommand sqlcmd3 = new SqlCommand(sqlUserName3, sqlcon);
sqlUserName4 = "SELECT in_date FROM status where s_id='"+TextBox2.Text+"'";
SqlCommand sqlcmd4 = new SqlCommand(sqlUserName4, sqlcon);
string q3 = sqlcmd3.ExecuteNonQuery().ToString();
string q4 = sqlcmd4.ExecuteNonQuery().ToString();
DateTime dt1 = DateTime.Parse(q3);
DateTime dt2 = DateTime.Parse(q4);
TimeSpan result = dt1.Subtract(dt2);
string result1 = result.ToString();
TextBox8.Text = result1;
//Response.Redirect("login.aspx");
sqlcon.Close();
There are many things wrong with your code at the moment:
You shouldn't use string concatenation to build your query. Use parameterized SQL instead. This will avoid SQL injection attacks and conversion issues
You're using ExecuteNonQuery when you're trying to execute... a query.
You're converting the results into a string which is a bad idea even if it did return a date... instead, get the results in a form you can fetch as just a DateTime. Avoid string conversions wherever you can.
So you should:
Use parameters instead of dynamic SQL
Use ExecuteReader and get the first result from each reader
Use the GetDateTime method to get the DateTime from the results.
I would personally use the subtraction operator afterwards, too:
TimeSpan difference = end - start;
... but that's just a matter of preference, and not an actual mistake in your current code.
Your mistake is here:
string q3 = sqlcmd3.ExecuteNonQuery().ToString();
string q4 = sqlcmd4.ExecuteNonQuery().ToString();
DateTime dt1 = DateTime.Parse(q3);
DateTime dt2 = DateTime.Parse(q4);
ExecuteNonQuery does not return a date in a string representation. It returns the number of records affected by the query; hence, when you run DateTime.Parse(number) you get an error.
None of your queries are returning a date so it's unclear how you expect to get a date back from calling the SQL you have in your question...
Update
Do not use string concatenation to build your SQL Statements. You can use parameters to avoid exposing yourself to SQL Injection attacks. One example would be:
string sqlUserName3 = "SELECT out_date FROM status where s_id=#id";
SqlCommand sqlcmd3 = new SqlCommand(sqlUserName3, sqlcon);
sqlcmd3.Parameters.AddWithValue("#id",TextBox2.Text );
You use SqlCommand.ExecuteNonQuery() but you need SqlCommand.ExecuteScalar(). The first function returns nothing, it's supposed to be used for queries like insert or update. The second returns value of first cell of first row of query output.
You should use execute scalar or pass some out parameter to get value. This should get you some value in q3 and q4.
Now to avoid erros you should also use DateTime.ParseExact instead of simple Parse.
DateTime dt1 = DateTime.ParseExact(q3,"dd/mm/yyyy HH:mm",CultureInfo.InvariantCulture);
DateTime dt2 = DateTime.ParseExact(q4,"dd/mm/yyyy HH:mm",CultureInfo.InvariantCulture);