I am not able to convert the c# date time7/31/2017 3:13:49 PM to SQL date time while inserting the records to the database.
I am doing this using
DateTime dt = DateTime.Parse("11/23/2010");
string toSqlDate= dt.ToString("yyyy-MM-dd HH:mm:ss");
DateTime finalDate = DateTime.Parse(toSqlDate);
But it's giving me the error.
String was not recognized as a valid DateTime.
The .Net DateTime maps directly to SQL Server DateTime. This means you don't need to worry about the display format at all, since DateTime does not have a display format.
All you need to do is pass the instance of the DateTime struct as a parameter to the SqlCommand:
SqlCommand.Parameters.Add("#DateTimeParam", SqlDbType.DateTime).Value = dt;
Bonus reading: How do I create a parameterized SQL query? Why Should I?
After changing it to year/month/date this can help!
var sqlDate = finalDate.Date.ToString("yyyy-MM-dd HH:mm:ss");
Your dateformat says 'year-month-day' while your date is 'month/day/year', that can't be right. Either change your dateformat or your date's formatting.
This should work:
DateTime dt = DateTime.Parse("2010-11-23 00:00:00");
string toSqlDate= dt.ToString("yyyy-MM-dd HH:mm:ss");
Change query to
insert into table_name (column1) values ('" + dt.Value.ToString("yyyy-MM-dd") + "')
Try the method DateTime.ParseExact and specify The date format that is suitable for you, here is an example from MSDN (https://msdn.microsoft.com/fr-fr/library/w2sa9yss(v=vs.110).aspx) :
var dateString = "06/15/2008";
var format = "d";
try {
var result = DateTime.ParseExact(dateString, format,
CultureInfo.InvariantCulture);
Console.WriteLine("{0} converts to {1}.", dateString,
result.ToString());
}
catch (FormatException)
{
Console.WriteLine("{0} is not in the correct format.", dateString);
}
Related
I have a date in this format "2017-03-29" and time like "09:30", How do I conver toDatetime.
Following is how I have
string date = "2017-03-29";
string time = "09:30"
I need to convert this to DateTime in c#.
I also need to compare this converted DateTime with current dateTime, I will be using this in comparison in Linq
Use DateTime.ParseExact. Also your problem statement and code shown have nothing to do with Linq. The code below assumes the hours are in 24 hour format, adjust accordingly if that is not the case and provide an am/pm flag.
string date = "2017-03-29";
string time = "09:30";
var dateTime = DateTime.ParseExact(date+time, "yyyy-MM-ddHH:mm", null);
I would say the same as #Sam, but I don't have enough reputation to comment.
string date = "2017-03-29";
string time = "09:30";
string dateTimeString = string.Format("{0} {1}", date, time);
DateTime dateTime = DateTime.ParseExact(dateTimeString, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
Note that the Kind of the resulting DateTime is DateTimeKind.Unspecified. Convert it as necessary.
Using the variables provided:
string dateTime = date + " " + time;
DateTime d = Convert.ToDateTime(dateTime);
I have a database date "2014-11-26". I have a calender with format(dd-MM-yyyy) I am trying to bring some values to my form from databse by textbox selected date
protected void txtdate_TextChanged(object sender, EventArgs e)
{
//DateTime timeIn = Convert.ToDateTime(txtdate.Text);
// DateTime time1 = DateTime.ParseExact(txtdate.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
str = "select TimeIn,TimeOut from MusterRoll where EmpCode='" + ddcode.SelectedItem.Text + "' and Date='"+time1+"'";
dr = conn.query(str);
if (dr.Read())
{
DateTime time = dr.GetDateTime(0);
TimeSelector1.SetTime(time.Hour, time.Minute, TimeSelector1.AmPm);
DateTime time2 = dr.GetDateTime(1);
TimeSelector2.SetTime(time2.Hour, time2.Minute, TimeSelector2.AmPm);
}
}
The problem is databse date format and my calender format is different. I tried two methods(which I placed in command line)but shows error message like "input string was not in correct format". I surfed internet and find these same answers. May I know why it shows error?? i am trying to make database dateformat and calender format as same
First of all, a DateTime doesn't have any implicit format. It has just date and time values. String representations of them can have a format.
I strongly suspect you save your DateTime values with their string representations which is a horrible idea. Read: Bad habits to kick : choosing the wrong data type Pass your DateTime values directly to your parameterized queries instead of their string representations. Anyway..
For;
DateTime timeIn = Convert.ToDateTime(txtdate.Text);
Convert.ToDateTime(string) method uses DateTime.Parse method with your CurrentCulture settings. That means if your string isn't a standard date and time format of your CurrentCulture your code throws FormatException. I guess dd-MM-yyyy is not a standard date and time format of your CurrentCulture.
For;
DateTime time1 = DateTime.ParseExact(txtdate.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
When you use DateTime.ParseExact, your string and format should match exactly.
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly or an exception is thrown.
In your case; they are not ("26-11-2014" and "yyyy-MM-dd"). Use dd-MM-yyyy format instead.
DateTime time1 = DateTime.ParseExact(txtdate.Text,
"dd-MM-yyyy",
CultureInfo.InvariantCulture);
Then you can generate the format from your time1 like;
time1.ToString("yyyy-MM-dd"); // A string formatted as 2014-11-26
For your command part, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
You can use this
var dateAndTime=Convert.ToDateTime(Txttradedate.Text).ToString("ddmmyyyy");
I am getting a string in the following format
string dt= "\"2014-06-01T05:00:00.000Z\""
I am trying to convert it to Date following way
mDateTime dt = Convert.ToDateTime(dt)
I get error saying When converting string to date time use parse the string.
Please let me know how I can parse the string to date. Thanks
Convert.ToDateTime method fails because this is not a standard date and time pattern for your CurrentCulture (And probably no culture support this format).
You can use custom date and time formatting with DateTime.TryParseExact or DateTime.ParseExact methods.
Here an example on LINQPad;
string s = "\"2014-06-01T05:00:00.000Z\"";
DateTime dt;
if(DateTime.TryParseExact(s, "'\"'yyyy-MM-dd'T'HH:mm:ss.fff'Z\"'",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
dt.Dump();
}
Output will be;
6/1/2014 5:00:00 AM
Here a demonstration.
At first you have to trim quotes, then parse:
DateTime result = DateTime.Parse(dt.Trim('\"'));
you can use below menioned code
string dt = "\"2014-06-01T05:00:00.000Z\"";
dt = dt.Replace("\"", "");
DateTime dt12 = Convert.ToDateTime(dt);
Try This:
string dt = "\"2014-06-01T05:00:00.000Z\"";
dt = dt.Replace("\"", "");
DateTime dtFinal = DateTime.ParseExact(dt,"yyyy-MM-ddTHH:mm:ss.fffZ",
CultureInfo.InvariantCulture);
I'm writing some dates to sql from a text file. In text file date format like 10.01.2013(dd.mm.yyyy) but when i write it on sql it seems `2013-01-10 what should to add it as 10.01.2013
Here is my code:
en.LogDateTime = DateTime.Parse(myDateString);
you can use the DateTime.ParseExact method to specify exactly what format your input string should be
DateTime dt = DateTime.ParseExact("10.01.2013", "MM.dd.yyyy", CultureInfo.InvariantCulture);
DateTimeFormatInfo dateformat= new DateTimeFormatInfo();
dateformat.ShortDatePattern = "dd.MM.yyyy";
dateformat.DateSeparator = ".";
DateTime objDate = Convert.ToDateTime(strDate, dateformat);
if you want to specify the format while inserting the data into table you can use following sql query:
dateformat dmy;
insert into mytable values(mydatetime);
Guys I have a string having a date in the format dd/mm/YYYY.
However I need to use it a datetimepicker control.
I cannot assign the value to the datetimepicker, i tried as
string exp = "SELECT UserPwdExpiry FROM " + MainForm.schema + "Adm.SysUser WHERE USerId ='" + cmbUserID.Text + "'";
cmd = ccs.CreateCommand();
ccs.Open();
cmd.CommandText = exp;
DateTime expiry_ = ((DateTime)cmd.ExecuteScalar());
//string _expiry_= expiry_.ToShortDateString();
ccs.Close();
assigning here
dtpPasswordExpiry.Value = Convert.ToDateTime(_expiry_);
It gives me an error saying, FORMAT SHOW BE BETWEEN MaxDate and MinDate.
Help please.
if DateTime expiry_ = ((DateTime)cmd.ExecuteScalar()); this line running without errors you already have Datetime object. So you can directly set it as
tpPasswordExpiry.Value =expiry_;
But above line will fail if you store datetime as string in database then
string _User_modify= (string)cmd.ExecuteScalar();
DateTime dt;
if(DateTime.TryParseExact(_User_modify,
"dd/MM/YYYY",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
tpPasswordExpiry.Value =dt;
}
We already have:
DateTime expiry = ((DateTime)cmd.ExecuteScalar());
so: we know the value is a DateTime. The DateTimePicker control's .Value property is a DateTime, so the correct syntax here is:
dtpPasswordExpiry.Value = expiry;
The only thing that leaves, based on the error message, is the MinDate and MaxDate. I suspect you need to change the values of those two properties such that your expiry is a legal value not outside the range MinDate - MaxDate. If unsure, simply print out the values of expiry, dtpPasswordExpiry.MinDate and dtpPasswordExpiry.MaxDate.