简体   繁体   中英

Microsoft Edge - C# Error - String was not recognized as a valid DateTime

Hi its facing issue with datetime formatting in my MVC Controller Get method. Its working fine when request send from Firefox, Chrome, Internet Explorer, But it throws an exception while request comes from Microsoft Edge browser :(

Exception : String was not recognized as a valid DateTime.

Sample Code is here -

public JsonResult GetFYDetailsForDate(string date)
{
    //input date = "6/13/2018"
    DateTimeStyles dateTimeStyles = DateTimeStyles.AssumeLocal;
    CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");

    var culturedDate1 = DateTime.ParseExact(date, "M/d/yyyy", new System.Globalization.CultureInfo("en-US"));

    var culturedDate = DateTime.Parse(date, culture, dateTimeStyles);

}

Imput Date is "6/13/2018" and Parsed Date output is "6/13/2018 12:00:00 AM" if request comes from Chrome, Firefox and Internet Explorer.

** To resolve this we can extract date, month and year from date string, but I don't want to do that. Just want to know what is wrong with request comes from Microsoft Edge browser.

Code screenshot - 在此处输入图片说明

There is a problem with input date string when it comes from Microsoft Edge browser. Date string contains characters (Char)8206 that's why C# unable to parse the date and throws an error. Visible length of string is 9, but actual length of string is 14. So I have removed those hidden characters from string and its working perfectly fine now.

Below code snippet I have used to sanitize string, please suggest any better and efficient way to do this.

Thanks you.

string sanitizedDateString = new String(inputDate.ToCharArray().Where(x => x != (Char)8206).ToArray());

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