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");
Related
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...
I have two parameters one for date and another for time, and i need date value part and time values part.
My two parameters are below.
// For Date parameter
DateTime dt = DateTime.ParseExact("01-jan-1999", "dd-MMM-yyyy", CultureInfo.InvariantCulture);
bo.Dateused5 = dt;
// For Time parameter
string Fromtiming = ddl_FromHours.SelectedItem.ToString() + ":" + ddl_FromMinutes.SelectedItem.ToString();
DateTime InterviewTime = Convert.ToDateTime(Fromtiming);//StartTime
bo.Dateused4 = InterviewTime;//InterviewTime
so i need to send mail to the candidate to only date part, should not contain time and time part, should not contain date.
are you looking for this:
DateTime dt = DateTime.ParseExact("01-jan-1999", "dd-MMM-yyyy", CultureInfo.InvariantCulture);
string mailDate = dt.ToString("dd-MMM-yyyy");// will give 01-jan-1999
string date = dt.ToString("dd-MM-yyyy"); // will give 01-01-1999
You can also try using String.Format()
string mailDate = String.Format("{0:dd-MM-yyyy}", dt); // will give 01-01-1999
You can use ToShortDateString():
DateTime dt = DateTime.ParseExact("01-jan-1999", "dd-MMM-yyyy", CultureInfo.InvariantCulture);
var date = dt.ToShortDateString();
Note that it uses date format attached to the current thread's culture info.
You would need to use strings rather than dates, so change the type of your variables to string so that
bo.Dateused5 = dt.ToString("dd-MMM-yyyy")
would set Dateused5 to a string of the date component, then
bo.Dateused4 = InterviewTime.ToString("HH:MM");
would set Dateused4 to the time component.
Couldn't test your code but I am very sure there are Functions "DateValue" and "TimeValue" you can make use of.
Something like,
Format(DateValue(any datetime), "dd-MM-yyyy")
gives you Only Date in the specified format. Similar way for TimeValue
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
I unable to convert string to date, my string like 17/12/2012
Code written for this is shown below
public string Date_Convert(string dt1)
{
string strdate = string.Empty;
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
DateTime dt = Convert.ToDateTime(dt1);
strdate = dt.Month.ToString() + "/" + dt.Day.ToString() + "/" + dt.Year.ToString();
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
return strdate;
}
It is working fine in my local system. And not working in my server(which is located at Australia)of course I tried with different culture settings in the above code,
I'm using this date string in sql query in where condition.
please help me, It killed my one day time, and thanks in advance.
Instead of switching the culture, why don't you do something like this:
public string Date_Convert(string dt1)
{
DateTime dt = DateTime.ParseExact(dt1, "dd/MM/yyyy", new CultureInfo("en-GB"));
return dt.ToString("d", new CultureInfo("en-US"));
}
Also: If you use the value in an SQL query (and provided that your query works on a DATETIME field, not NVARCHAR), you should also consider using a parameterized query to pass the DateTime value to the database to avoid SQL injection.
For example:
DateTime value = DateTime.Parse(dt1, new CultureInfo("en-GB"));
using (SqlCommand cmd = new SqlCommand("SELECT ... FROM ... WHERE Date = #date", connection))
{
cmd.Parameters.AddWithValue("#date", value);
...
}
Try DateTime.ParseExact() it receives as parameter the pattern so for your case it would be "dd/MM/yyyy"
The format of the DataTime will depend on the current culture of your application. Inorder to have a specific format throught your application you can set the tag in the web.config file under section. In such case you need not write code to convert the datatime to proper format. By default all the dates will be set to the format specified.
http://forums.asp.net/t/1109183.aspx/1
More Info
I'm trying to convert dates for example 30/12/2000 to 2000-12-30
using this code:
System.Globalization.CultureInfo enUS = new System.Globalization.CultureInfo("en-US");
DateTime.ParseExact(row.Cells[6].ToString(), "yyyy-MM-dd", enUS);
But I'm getting this error:
String was not recognized as a valid DateTime.
Can someone help me please, Thank you in advance.
You could use DateTime.TryParse() function and check if result is true or false.
So you could try to parse date with a specified format and, if its not right, try another one and so on...
The reason why you are getting this is exactly as the exception says, the string is in an incorrect format, the reason is most likely that the machine doing the comparison has a different date time setting to yyyy-MM-dd.
If you are retrieving this from a database and the return value is of date time (or if you know that row.Cells[6] is a DateTime Field, the following should work:
System.Globalization.CultureInfo enUS = new System.Globalization.CultureInfo("en-US");
if (row.Cells[6] != null)
DateTime.ParseExact(((DateTime)row.Cells[6]).ToString("yyyy-MM-dd"), "yyyy-MM-dd", enUS);
The question is however why would you want to change the format, to display it on a form if so then you can just display it as follows:
if (row.Cells[6] != null)
TextBox1.Text = ((DateTime)row.Cells[6]).ToString("yyyy-MM-dd");
EDIT
Given that row.Cells[6] is a string, you will always have to know what the format of the string is, and if you do then it would be as simple as:
With time:
DateTime ParsedDate = DateTime.ParseExact(row.Cells[6].ToString(), "dd-MM-yyyy h:mm", enUS);
Removing time and then parsing:
DateTime ParsedDate = DateTime.ParseExact(row.Cells[6].ToString().Substring(0,10), "dd/MM/yyyy", enUS);
and then to output it in the format you want would be as simple as:
TextBox1.Text = ParsedDate.ToString("yyyy-MM-dd");
You are specifying a en-US CultureInfo object, but 30/12/2000 is not a correct US date format
Try this may resolve your issue
String oldScheduledDate = "16-05-2011";
DateFormat oldFormatter = new SimpleDateFormat("dd/MM/yyyy");
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
try
{
Date oldDate = (Date)oldFormatter .parse(oldScheduledDate);
}
Catch(Exception ex ) { /// process exception}
System.Globalization.CultureInfo enUS = new System.Globalization.CultureInfo("en-US");
try {
DateTime.ParseExact(row.Cells[6].ToString(), "yyyy-MM-dd", enUS);
}
catch (FormatException) {
...your code instead of error...
}
I believe that the problem is your second parameter. If you are passing 30/12/200 as your input, it will fail because the second parameter is expecting it separated with dashes.
use
System.Globalization.CultureInfo.InvariantCulture
DateTime.ParseExact(((DateTime)row.Cells[6]).ToString("yyyy-MM-dd"), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture)
;
you forgot the hours / minutes:
from the DB it comes like that (converted to string) "12/05/2011 0:00"
DateTime.ParseExact(theCellValue, "MM/dd/yyyy HH:mm", enUS).ToString("yyyy-MM-dd")
creates the string you want, but its totally stupid. you should just make sure that the datetime gets in the first place formatted as you want. (then you never have to parse it)
If your source string is in dd/MM/yyyy, then you shouldn't be using US culture (MM/dd/yyyy) to parse the string.
System.Globalization.CultureInfo enGB = new System.Globalization.CultureInfo("en-GB");
DateTime temp = DateTime.ParseExact(row.Cells[6].Text, "dd/MM/yyyy", enGB);
row.Cells[6] = temp.ToString("yyyy-MM-dd");
Put this in the RowDataBound event of your grid.
I fixed it by using
Convert.ToDateTime(row.Cells[6].Text)
See how simple it is.