简体   繁体   中英

For valid DateTime(Error shows string was not recognized )

I am trying to convert my string formated value to date type with format dd/MM/yyyy. It runs fine but when I enter fromdate(dd/MM/yyyy) in textbox its fine and todate(dd/MM/yyyy) in textbox then it gives an error that string was not recognized as a valid datetime.What is the problem exactly i dont know. same code run on another appliction its run fine but in my application it shows Error.

Below I have used array for required format and split also used.

string fromdate = punchin.ToString();
string[] arrfromdate = fromdate.Split('/');
fromdate = arrfromdate[1].ToString() + "/" + arrfromdate[0].ToString() + "/" + arrfromdate[2].ToString();
DateTime d1 = DateTime.Parse(fromdate.ToString());

try with DateTime.TryParseExact as below

DateTime date;
if (DateTime.TryParseExact(inputText, "MM/dd/yyyy",
                           CultureInfo.InvariantCulture,
                           DateTimeStyles.None,
                           out date))
{
   // Success
}

if you know the format of input date time you don't need to do any string manipulation. But you need to give correct Date and Time Format String

Try :

DateTime.ParseExact(fromdate, "MM/dd/yy", CultureInfo.InvariantCulture) 

Obviously you can reformat the above, and use different providers by creating an instance of CultureInfo related to the string you are parsing, and you can modify the format string to reflect that culture or to accommodate more date parts

I got 5/13/2013 12:21:35 PM in string fromdate

Use DateTime.TryParseExac t, You don't have to split your string based on / and then get first three items from the array instead you can simply do:

DateTime dt;
if (DateTime.TryParseExact("5/13/2013 12:21:35 PM",
                                  "M/d/yyyy hh:mm:ss tt",
                                  CultureInfo.InvariantCulture,
                                  DateTimeStyles.None,
                                  out dt))
{
    //date is fine
}

Using single d and single M as it can accomodate single digit as well as double digits day/Month part. You can simply pass punchin as the string parameter, Calling ToString on string types is redundant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM