How to extract time from Datetime - c#

Im trying to extract time from Datetime and then converting it into int to add 10 to it and then convert it into Datetime and store in the database. But I keep getting following error:
"String was not recognized as a valid DateTime."
Following is the code:
MySqlConnection conn = new MySqlConnection(connection);
String query = "Select timings from topogen.token_gen order by timings desc limit 0,1;";
MySqlCommand cmd = new MySqlCommand(query, conn);
String location = "";
conn.Open();
MySqlDataReader r = cmd.ExecuteReader();
string timings="";
while( r.Read()){
timings = r["timings"].ToString();}
DateTime time = DateTime.Parse(timings); //error appears here
timings = time.ToString("HH:mm:ss");
time = DateTime.Parse(timings);
long t = time.Ticks;
t += 10;
timings = t.ToString("HH:mm:ss");
TextBox1.Text = timings;
time = DateTime.ParseExact(timings, "HH:mm:ss", null);
this.Location = location;
conn.Close();

Looks like your r["timings"].ToString() generates a string representation that your CurrentCulture does not have a standard date and time format. That's why your DateTime.Parse throws FormatException.
Change your timings column type to datetime type even it doesn't.
Use GetDateTime() method of MySqlDataReader to get it's value as DateTime
MySqlDataReader r = cmd.ExecuteReader();
if(r.Read())
{
DateTime timings = r.GetDateTime(0);
}
Let's look the rest of your code. They have also some mistakes.
long t = time.Ticks;
With this, you will get Ticks of your DateTime which looks like for example; 2,193,385,800,000,000.
t += 10;
With this, you will get 2,193,385,800,000,010 which is okey for now because it is a long and this is just an addition.
timings = t.ToString("HH:mm:ss");
Here a mistake. You try to get string representation of your long which uses NumberFormatInfo of your CurrentCulture. It doesn't even use DateTimeFormatInfo. That's your your timings will be HH:mm:ss as a string. And you will try to parse it as DateTime.ParseExact(timings, "HH:mm:ss", null) which is equal to DateTime.ParseExact("HH:mm:ss", "HH:mm:ss", null). As you can see, this parsing operation will fail.
Consider to changing your logic.

Related

String was Not recognised as valid date time C#

I created a web app which is working fine on localhost but when I uploaded the web app, I get an error on my calender
String was not recognized as a valid DateTime.
Line 1291: string strstartdate = "";
Line 1292: strstartdate = txtfrmdate.Text;
Line 1293: DateTime dt = Convert.ToDateTime(strstartdate);
Line 1294: string strfstartdate = dt.ToString(strstartdate);
Line 1295: DateTime dtnew = Convert.ToDateTime(strfstartdate);
It is working fine with the date range of (1/12), but when I choose date between (13/31), I get this error.
This is what is selected (13-09-2016)
My C# page
string strstartdate = "";
strstartdate = txtfrmdate.Text;
DateTime dt = Convert.ToDateTime(strstartdate);
string strfstartdate = dt.ToString(strstartdate);
DateTime dtnew = Convert.ToDateTime(strfstartdate);
SqlCommand cmd = new SqlCommand("csuvdaterange");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
con.Open();
SqlParameter[] param =
{
new SqlParameter("#logintype",com.ToString()),
new SqlParameter("#name",lblempname.Text),
new SqlParameter("#datefrm",DateTime.ParseExact(txtfrmdate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd")),
new SqlParameter("#dateto",DateTime.ParseExact(txttodate.Text,"dd-MM-yyyy",CultureInfo.InvariantCulture).ToString("yyyy-MM-dd"))
};
The CurrentCulture on the web server would appear to be US, and your text isn't in a format where month precedes the day - it's inferring a month of 13, which isn't a valid date.
You should parse the date the same way as your do later in your code:
DateTime.ParseExact(txtfrmdate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture)
Use DateTime.ParseExact instead of Convert.ToDateTime
in order to avoid system from confusion on different regional date format settings I recommend that date format be always mentioned while converting types...

Which SQL Date format

Which date format does T-SQL use? Does it rely on the system date? How can I be sure that my parameters are passed on correctly regardless of system date format. This question comes because of error:
Error converting data type nvarchar to datetime.
The SQL script in part:
CREATE PROCEDURE [dbo].[sz_pipeline04_pipelUpdte_inventory]
-- Add the parameters for the stored procedure here
#myFixDte datetime,
#doInsert bit
AS
BEGIN
The calling c# code:
public static DataTable GridInventory(string strdProcedureName, DateTime fixDate, bool execInsertYN)
{
DataTable dtbl_inventory = null;
try
{
dtbl_inventory = new DataTable();
using (var conn = new SqlConnection(cls_connRegistry.GetConnStrFull()))
using (var command = new SqlCommand(strdProcedureName, conn)
{
CommandType = CommandType.StoredProcedure
})
{
command.Parameters.Add("#myFixDte", SqlDbType.DateTime).Value = DateTime.Parse(fixDate.ToShortDateString());
command.Parameters.Add("#doInsert", SqlDbType.Bit).Value = execInsertYN;
conn.Open();
SqlDataReader dr = command.ExecuteReader();
dtbl_inventory.Load(dr);
conn.Close();
}
}
catch (Exception datawalile)
{ dtbl_inventory = null; }
return dtbl_inventory;
}
edited question.
The code you've now posted looks correct - except for one thing:
command.Parameters.Add("#myFixDte", SqlDbType.DateTime).Value = DateTime.Parse(fixDate.ToShortDateString());
As I've said in the comments, issues only come up around formatting when you convert to strings. So just do:
command.Parameters.Add("#myFixDte", SqlDbType.DateTime).Value = fixDate;
DateTimes (C#) and datetime (T-SQL) don't have a format. You get formatting issues when you convert them into strings. In their native representation, they're usually just a count of a number of events (ticks, milliseconds, etc) since some fixed point in the past. ADO.Net knows how to convert a DateTime into a SQL Server datetime.
If you have remaining conversion issues, it's in code you've not yet shown. But it will, again, be because you're converting away from the correct data type (datetime) and using strings.
This is not valid DATETIME format DD-MM-YYYY.
You can use CONVERT It in following:
DECLARE #myFixDte DATETIME
SET #myFixDte = CONVERT(DATE, N'30-12-2012', 104)
SELECT #myFixDte
Or you can SET It without converting in other format like YYYY-MM-DD
Try this:
#myFixDte = convert(datetime, '30-12-2012', 105)
And check the link provided by #N.Molderf
SQL Server recognizes one format always in same way, regardless which culture it using, and that format is YYYYMMDD.
So you can always use your dates in format 20120202 or 20151225, and SQL Server will parse that parameter using same mask.
Why you didnt tell as above c# datetime, here is a simple example for you how to solve this problem in your case it will be something like this
DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("dd-MM-yyyy HH:mm:ss");
or this one
DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss");
second one is a default

how to convert datetime format

hi i am giving a textbox to user and ajax calender extender to select date in dd/mm/yyyy format after that i am using following function to convert it to mm/dd/yyyy format for inserting in to sql server database but it not work well in one page i got error datetime conversion error and in other i have to enter yyyy/mm/dd format to insert data into database. my code works fine in localhost but in server these errors are coming . my function is
protected string getDate_MDY(string inDate)
{
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-GB");
DateTime dtProjectStartDate = Convert.ToDateTime(inDate);
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
return (Convert.ToDateTime(dtProjectStartDate).ToString("MM/dd/yyyy"));
}
and for inserting i used it like getDate_MDY(txtcreatedate.text);
i just want to insert my correct date in to database by taking dd/mm/yyyy format from text box. . please show me right way to modify it...thanks
Use DateTime.Parse or DateTime.ParseExact instead of changing the current thread culture. Both of these methods have overloads that take a culture to use when parsing the string.
For example:
protected string getDate_MDY(string inDate)
{
DateTime date = DateTime.Parse(inDate, new CultureInfo("en-GB"));
return date.ToString("MM/dd/yyyy", new CultureInfo("en-US"));
}
This isn't the most efficient way to do this (you'd probably want to cache the CultureInfo instances for starters) but it will do what you asked for (ie. convert a date/time string from one culture to another).
However, as someone pointed out in the comments, you shouldn't be passing date strings to a SQL command. Instead, they should be defined as date/time parameters in the SQL command:
using (var connection = new SqlConnection("<your connection string>"))
using (var command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO (sometable) VALUES (#somedatecolumn)";
command.CommandType = CommandType.Text;
var parameter = new SqlParameter("#somedatecolumn", SqlDbType.SmallDateTime);
parameter.Value = <your date/time value>; // a DateTime value, not a string
command.Parameters.Add(parameter);
command.ExecuteNonQuery();
}
It seems that you should only add DateTimeFormatInfo to your Convert.ToDateTime(inDate) --> Convert.ToDateTime(inDate, DateTimeFormatInfo)
System.Globalization.DateTimeFormatInfo dtfi = null;
DateTime dtProjectStartDate = new DateTime(2008, 4, 10); //year, month, day
ci = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB");
dtfi = ci.DateTimeFormat;
txtBox.Text = dtProjectStartDate.ToString("d", dtfi); // 10/4/2008
System.Globalization.CultureInfo ciForSQL = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
System.Globalization.DateTimeFormatInfo dtfiForSQL = ciForSQL.DateTimeFormat;
DateTime dtForSQL = Convert.ToDateTime(txtBox.Text, dtfiForSQL);
txtBoxForSQL.Text = dtForSQL.ToString("d", dtfiForSQL); // 10/4/2008
Use..DateTime.ParseExact
DateTime.ParseExact("12/02/21 10:56:09", "yy/MM/dd HH:mm:ss",
CultureInfo.InvariantCulture
).ToString("MM/dd/yyyy");

Conversion failed when passing date/time object to SQL

I am trying to add new information to a table, but it is giving me this Conversion failed error when converting date/time from character to string.
Here is part of my code:
try
{
string sp = "add";
comando.CommandType = CommandType.StoredProcedure;
comando.CommandText = sp;
comando.Parameters.Clear();
comando.Parameters.Add(new SqlParameter("#person", SqlDbType.VarChar));
comando.Parameters.Add(new SqlParameter("#reason", SqlDbType.VarChar));
comando.Parameters.Add(new SqlParameter("#information", SqlDbType.VarChar));
comando.Parameters.Add(new SqlParameter("#date", SqlDbType.DateTime));
comando.Parameters[0].Value = obj.person;
comando.Parameters[1].Value = obj.reason;
comando.Parameters[2].Value = obj.information;
comando.Parameters[3].Value = obj.date;
comando.ExecuteNonQuery();
}
catch (Exception exc)
{
throw exc;
}
To get the information of the date I am using obj.date = DateTime.Now; is this correct?
I don't recall how or why sometimes sending a plain date/time object into SQL won't work as we expect it.
The solution is to convert the date/time object to the universal ISO 8601 format: yyyyMMdd HH:mm:ss.fff - which SQL absolutely loves.
Here's a snippet which takes from J W's answer, which is actually demonstrating best practice:
const String UniversalDateTime = "yyyyMMdd HH:mm:ss.fff";
comando.CommandType = CommandType.StoredProcedure;
comando.CommandText = sp;
comando.Parameters.AddWithValue("#person", obj.person);
comando.Parameters.AddWithValue("#reason", obj.reason);
comando.Parameters.AddWithValue("#information", obj.information);
comando.Parameters.AddWithValue("#date", obj.date.ToString(UniversalDateTime));
// assuming connection is already open
comando.ExecuteNonQuery();
Upon SQL receiving the date/time string representation, the value will automatically be converted to SQL's internal date/time value.
PS. I recall also trying the ISO 8601 format using the T as separator: yyyyMMddTHH:mm:ss.fff. Try the version with the space, which worked for me when using the en-US SQL locale and non-en-US locales too.
Alternatively, you can use AddWithValue()
comando.CommandType = CommandType.StoredProcedure;
comando.CommandText = sp;
comando.Parameters.AddWithValue("#person", obj.person);
comando.Parameters.AddWithValue("#reason", obj.reason);
comando.Parameters.AddWithValue("#information", obj.information);
comando.Parameters.AddWithValue("#date", DateTime.Now);
// assuming connection is already open
comando.ExecuteNonQuery();

Failed to convert parameter value from string to datetime

myCommand1.Parameters.Add("#I_vBACHNUMB", SqlDbType.Char).Value = GLHdr.BACHNUMB;
myCommand1.Parameters.Add("#I_vREFRENCE", SqlDbType.Char).Value = "ExcelImport";
myCommand1.Parameters.Add("#I_vTRXDATE", SqlDbType.DateTime).Value = GLHdr.TRXDATE;
In last line I have value GLHdr.TRXDATE: "15-02-2017".
I am getting format exception.Let me know where I am doing mistake.
GLHdr.TRXDATE is a string, not a DateTime.
You need to parse it into a DateTime before passing it through:
var dt = DateTime.Parse(GLHdr.TRXDATE);
myCommand1.Parameters.Add("#I_vTRXDATE", SqlDbType.DateTime).Value = dt;
Note that DateTime.Parse can fail, so ParseExact or TryParseExact that also take a format string may be more suitable for you specific circumstances.

Categories