String was no recognized as a valid Date TIme Erro

2019-09-03 15:32发布

问题:

I have developed an application which is compatible with .net Framework 3.5 to run the build of it in other applications also.

The O. S. of built application is Windows 7.

And when I run the build in Windows XP this error occurs for following code:

dtBillDate.Text = ds.Tables[0].Rows[0]["Dt"].ToString(); 

Here dtBillDate is a DateTimePickerControl.

And the SQL query to fill ds records is:

query = "Select M.BillNo,M.PartyName,M.Address,M.City,M.State,M.TaxType,
M.BillType,FORMAT(M.BillDt,'dd-mm-yyyy')as Dt,
M.CST,M.GST,M.TransportName,M.TruckNo,M.Through,M.Tax,M.AddTax,M.Charges from BillMaster M where M.BillNo=" + billNo;

Records are stored in the Access 2007 database.

What changes I should make to tackle the error.

Please help. Thanks in advance.

回答1:

You are formatting your Date in your query

FORMAT(M.BillDt,'dd-mm-yyyy')as Dt

In your format mm should MM, since you probably need month, not minutes

You should use DateTime.ParseExact with the format dd-MM-yyyy to parse the date. Although its better if you let your query return the DateTime without formatting, and let .Net application format your date for displaying.

You need to set DateTimePicker control value to show the date. You can use DateTime.ParseExact to parse like:

dtBillDate.Value = DateTime.ParseExact(ds.Tables[0].Rows[0]["Dt"].ToString(), 
                                       "dd-MM-yyyy", 
                                       CultureInfo.InvariantCulture);


回答2:

Try this:

DateTime dateTime;
string dateString = ds.Tables[0].Rows[0]["Dt"].ToString();
bool result = DateTime.TryParse(dateString , out dateTime);

if(result)
{
     // Use `dateTime` variable then
}


回答3:

Basically in win 7 the "English INDIA " format is available, in which the date separator is "-". But in Win XP " English India" Format is not available, so u might be using " English US or UK" format for date which use "/" as a date separator.

TO Solve your problem ,all you gotta do is change the date separator format to "-" in your win xp machine by going to > CONTROL PANEL>REGION AND LANGUAGE OPTIONS> Click On "Customize" > OPEN The "DATE" Tab and here set the DATE SEPARATOR to "-". And Your Application Will Work Without any error. Happy Now :D