How to get short date format from the datetime object - c#

I am capturing the time in the text box (by using AJAX calender extender)
the time in the string is 12/10/2013, but when I assign the string to a datetime object it is converted into 12/10/2013 12:00:00 AM.
I want to use the date to filter the records in the database using the query below. Please help
string date1 = txtDate1.Text;
DateTime date = DateTime.ParseExact(txtDate1.Text, "MM/dd/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
string strQuery = "SELECT Story.UserName,Story.StoryId,COUNT(Likes.StoryID) AS NumberOfOrders
FROM Likes LEFT JOIN Story ON Likes.StoryId=Story.StoryId and liked=" + date1 + "
GROUP BY Story.StoryId,Story.UserName order by NumberOfOrders DESC ;";

It's generally not a good idea to pass dates as strings in your queries because you will most likely run into formatting issues - leave it up to the Framework you are using decide on what the best format is.
In your circumstances, you can do this by using SqlParameters e.g.
DateTime date = DateTime.ParseExact(txtDate1.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture);
string strQuery = "SELECT Story.UserName, Story.StoryId, COUNT(Likes.StoryID) AS NumberOfOrders
FROM Likes LEFT JOIN Story ON Likes.StoryId=Story.StoryId and liked=#dateTime
GROUP BY Story.StoryId,Story.UserName order by NumberOfOrders DESC";
using (SqlConnection connection = new SqlConnection("..."))
{
using (SqlCommand cmd = new SqlCommand(strQuery, connection))
{
cmd.Parameters.AddWithValue("#dateTime", date);
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
...
}
}
Another important reason to use parameters when writing raw SQL is to ensure your user input is correctly sanatized and safe to pass to the DB. Failure to do this can leave you open to various exploitations such as SQL Injection.

Instead of DateTime object you can use Date object.
DateTime is an integer interpreted to represent both parts of DateTime (ie: date and time). You will always have both date and time in DateTime.
ex:
DateTime.Now.ToString("MM/dd/yyyy");

Related

Datetime Update format error Asp.Net

I have an italian format datetime string like this:
23/03/2012
the sql command of this update is this in the datetime part:
DateTime.ParseExact(Reg_tes.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture)
This works on my Sql server(Italian language) but if i make this on my server(English language) gives me this error:
"the conversion of a varchar data type to a datetime data type
resulted in an out-of-range value"
How can I resolve this?
You should always use parameterized queries to prevent sql-injection and localization issues like this.
So i assume that you are passing this datetime as string to the database.
using(var con = new SqlConnection("connection-string"))
using(var cmd = new SqlCommand("UPDATE dbo.TableName SET DateColumn=#DateColumn WHERE PK=#PK", con))
{
DateTime reg_tes = DateTime.ParseExact(Reg_tes.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
cmd.Parameters.AddWithvalue("#DateColumn", reg_tes);
// other parameters ...
con.Open();
int affected = cmd.executeNonQuery();
}

Error in accessing the date in asp.net

DateTime startDate = DateTime.ParseExact(txtstart.Text, "yyyyMMdd", null);
DateTime endDate = DateTime.ParseExact(txtend.Text, "yyyyMMdd", null);
SqlDataAdapter adapter = new SqlDataAdapter(
"select * from Membership_det where updateDate between "+
startDate.ToString() + " and "+ endDate.ToString() +" ", con);
It gives error:
String was not recognized as a valid DateTime.When date is entered in
mm/dd/yyyy format
Well yes - you're explicitly specifying that you want to parse it in yyyyMMdd format. I don't see why you'd expect it to work if you've actually specified it in MM/dd/yyyy format. If you want to handle that instead, change your parsing code:
DateTime startDate = DateTime.ParseExact(txtstart.Text, "MM/dd/yyyy",
CultureInfo.InvariantCulture);
DateTime endDate = DateTime.ParseExact(txtend.Text, "MM/dd/yyyy",
CultureInfo.InvariantCulture);
However:
If this is parsing user input, you should use DateTime.TryParseExact instead, so you can detect errors in the input in the normal flow instead of using exceptions.
This code is very US-centric; non-US users may well find it confusing. In general you'd either be better off using one of the standard date formats (and the user's culture) or even better, using a date picker control of some form, to avoid the whole text format issue to start with.
Next you're using the values directly in the SQL statement. Don't do that. Always, always, always use parameterized SQL:
SqlDataAdapter adapter = new SqlDataAdapter(
"select * from Membership_det where updateDate between #Start and #End",
con);
adapter.SelectCommand.Parameters.Add("#Start", SqlDbType.Date).Value = startDate;
adapter.SelectCommand.Parameters.Add("#End", SqlDbType.Date).Value = endDate;
(Or create the command first and then pass that to the adapter.)
Using parameterized SQL has three benefits:
It avoids SQL injection attacks
It avoids data conversion issues (which are common with dates)
It keeps your SQL easy to read by separating the code from the data
Access DB Only
DateTime startDate = DateTime.ParseExact(txtstart.Text, "MMddyyyy", null);
DateTime endDate = DateTime.ParseExact(txtend.Text, "MMddyyyy", null);
SqlDataAdapter adapter = new SqlDataAdapter(
"select * from Membership_det where format( updateDate,'MM/dd/yyyy') between '"+
startDate.ToString("MM/dd/yyyy") + "' and '"+ endDate.Tostring("MM/dd/yyyy") +"' ", con);
Sql Server
DateTime startDate = DateTime.ParseExact(txtstart.Text, "MMddyyyy", null);
DateTime endDate = DateTime.ParseExact(txtend.Text, "MMddyyyy", null);
SqlDataAdapter adapter = new SqlDataAdapter(
"select * from Membership_det where Convert(varchar(15), updateDate,106) between '"+
startDate.ToString(dd MMM yyyy) + "' and '"+ endDate.Tostring(dd MMM yyyy) +"' ", con);

Search datetime in MySQL

I have a MySQL database, there's a table which have column Time's Type is Nvachar(50) and its values is kind like this "05/09/2012 20:53:40:843" *(Month-date-year hour:mins:second:msecond)*
Now I want to query to get a record have Time after "10/05/2012 01:00:30 PM".
I had code in C# to converted it to "05/10/2012 13:00:30" before making a query.
My Query :
SELECT * FROM ABCDFEGH WHERE capTime > '05/10/2012 13:00:30' LIMIT 0, 1
But i got no record. So please tell me how can I can make it return record have time after the time above ???
More Info My C# code :
string tableName = "ABCDFEGH";
string date = "05/10/2012 13:00:30";
var query = "SELECT * FROM " + tableName + " WHERE capTime > '" + date + "' LIMIT 0, 1";
var cmd = new MySqlCommand(query, connection);
MySqlDataReader dataReader = null;
try
{
dataReader = cmd.ExecuteReader();
}
I'm so so so so so so sorry. I made a mistake the query must be
SELECT * FROM ABCDFEGH WHERE capTime > '05/10/2012 13:00:30' LIMIT 0, 1
This query is successful return the record i need :)
But soemhow I have mistyped it into
SELECT * FROM ABCDFEGH WHERE capTime > '05-10-2012 13:00:30' LIMIT 0, 1
Sorry again, topic close. But tks for evveryone tried :)
I recommend using the DATETIME datatype instead of NVARCHAR. Store dates in YYYY-MM-DD HH:MM:SS format, which is the native DATETIME format recognized by MySQL.
Also use date literals in the same format.
Two reasons for this recommendation: First, DATETIME takes only 8 bytes, instead of up to 150 bytes which is the potential size of a multibyte 50 character varchar.
Second, the sort order of DATETIME will be the same as the chronological order. So if you create an index on the Time column, your > comparison can benefit from the index. Your query will be much faster as a result.
Use TIMESTAMPDIFF()
Schema
CREATE TABLE ABCDFEGH (`right` varchar(3), `time` datetime);
INSERT INTO ABCDFEGH (`right`, `time`)
VALUES
('Yes', '2012-10-02 13:00:30'),
('No', '2012-10-15 13:00:30');
SQL Code
SELECT * FROM ABCDFEGH
WHERE TIMESTAMPDIFF(MINUTE, time, '2012-10-05 13:00:30') > 0
LIMIT 0, 1
Explanation
TIMESTAMPDIFF() returns datetime_expr2 – datetime_expr1, where datetime_expr1 and datetime_expr2 are date or datetime expressions. One expression may be a date and the other a datetime; a date value is treated as a datetime having the time part '00:00:00' where necessary. The unit for the result (an integer) is given by the unit argument.
Fiddle: http://www.sqlfiddle.com/#!2/244cc/1 datetime
Fiddle: http://www.sqlfiddle.com/#!2/063b3/1 varchar(50)
PS1: Time may be a reserved word. Please avoid using it. Else use it with backticks (`).
PS2: The format of time is YYYY-MM-DD not the reverse.
First, why did you save the dates as NVARCHAR? If you are still able to change it to DATETIME datatype and all of the records on it, much better.
But if not, you can use STR_TO_DATE.
SELECT *
FROM tableName
WHERE STR_TO_DATE(`capTime`, '%m/%d/%Y %H:%i:%s:%x') >
STR_TO_DATE('05/10/2012 13:00:30', '%c/%d/%Y %H:%i:%s')
See SQLFiddle Demo
SOURCES
STR_TO_DATE
DATE Formats
UPDATE 1
and your query is vulnerable with SQL Injection. To avoid from it
Parameterized your query
code snippet,
string tableName = "ABCDFEGH";
string date = "05/10/2012 13:00:30";
String query = "SELECT * FROM " + tableName + " WHERE STR_TO_DATE(`capTime`, '%m/%d/%Y %H:%i:%s:%x') > STR_TO_DATE(#dateHere, '%c/%d/%Y %H:%i:%s')";
using (MySqlConnection connection = new MySqlConnection("connectionStringHere"))
{
using (MySqlCommand command = new MySqlCommand())
{
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = query;
command.Parameters.AddwithValue("#dateHere",date)
MySqlDataReader dataReader = null;
try
{
dataReader = cmd.ExecuteReader();
}
catch(MySqlException e)
{
// do something here
// don't suppress the error
}
}
}

Insert date into SQL without taking care of the regional settings

my question looks simple: in my client/server application I want to record a specific date provided by the client.
The problem is that I don't know the regional settings of the client, and I don't know the regional settings of the SQL Server.
How can the client application provide a date in whatever format (last login of a specific user) and store it in a SQL Server table that might be installed with a different regional settings (french, english, italian, german, etc...).
Simple: don't use strings. Use a parameter that is typed as a datetime; can be as simple as:
DateTime when = ...
using(var cmd = conn.CreateCommand()) {
cmd.CommandText = "... #when ...";
cmd.Parameters.AddWithValue("when", when);
cmd.ExecuteNotQuery();
}
or with "dapper":
conn.Execute("... #when ...", new { when });
Dates/times are actually just numbers. It is only when you write/parse it as a string that formatting is an issue.
Just store everything in UTC date in sqlserver. And while retrieving the date convert the utc date to the timezone of the user. I hope users timezone is maintained in your database.
You will need a timezone table and a conversion function that will convert the UTC time to the users local time.
to insert a date in SQL use a string in the form 'YYYYMMDD'
what comes from the client-side you sould know what is it
You should use Parameters, but you also can format date to ISO format by date.ToString("s")
Use datetime format, and store dates as UTC time.
You'll probably also be interested in datetimeoffset.
Validation part
DateTime dt;
string YourDate = "Your Date";
if (DateTime.TryParse(YourDate, out dt))
{
//Your Code
}
Stored Procedure Record Insertion/Retrieval
using (System.Data.SqlClient.SqlConnection con = new SqlConnection("YourConnection string"))
{
con.Open();
SqlCommand cmd = new SqlCommand();
string expression = "Date Parameter value";
DateTime dt;
if (DateTime.TryParse(expression, out dt))
{
//Your Code
}
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Your Stored Procedure";
cmd.Parameters.Add("Your Parameter Name", SqlDbType.VarChar).Value = expression;
cmd.Connection = con;
using (IDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
}
}
}
While storing the data in Sql Server Keep the data format consistent and synchronized with the data format while retrieving....

inserting datetimepicker value to SQL Server 2008

I'm trying to insert a value from a datetimepicker value to a SQL Server table.
My table looks like this
Profile (Id, Name,..., DateofBirth(date)...)
I have tried this to convert datetime picker value to
string dt = dateTimePicker.Value.ToString("yyyy-mm-dd hh:MM:ss");
Insert into profile (id, DateofBirth)
values(id, CONVERT(datetime, CONVERT( varchar(11), dt, 101));
also use this
var date = new DateTime(dateTimePickerText);
also use this
DateTime date = DateBox.Value.Date;
string sDate = date.ToString("dd-MM-yy", System.Globalization.CultureInfo.InvariantCulture);
DateTime dateInsert = Convert.ToDateTime(sDate);
but can't able to insert the date into the database. 2nd how can I retrieve back the date from database?
You must have to use SqlParameter.
sql="Insert into profile (id, DateofBirth) values (#id,#DateofBirth)";
using(SqlCommand cmd=new SqlCommand(sql,conn))
{
cmd.Parameters.Add("#id",SqlDbType.Int).Value=10;
cmd.Parameters.Add("#DateofBirth",SqlDbType.DateTime).Value=dateTimePicker.Value;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
Personally I'd get into the habit of using parameters for all of your SQL queries. That way you avoid SQL injection attack vector and you can also specify the parameter type as datetime. See this answer for example.

Categories