We Help You To Renovate Your Blogger Blog With Awesomeness!

Showing posts with label String was not recognized as a valid DateTime. Show all posts
Showing posts with label String was not recognized as a valid DateTime. Show all posts

Monday, September 29, 2014

  • Datetime format Issue String was not recognized as a valid DateTime C# ASP .Net


    If this issue happens after the website is uploaded to server and no problem at your local computer, the cause of error is the date format difference of your system and your server

    Mostly the error happens for month

    consider a date "29/09/2014 20:20:00"

    Usually this error occurs at Convert.ToDateTime(DateTimeInStringFormat);

    My local computer consider '29' as day and my server consider '29' as a month.

    ie. at my local server date format is 'dd/MM/yyyy HH:mm:ss'

    and at server it is 'MM/dd/yyyy HH:mm:ss'

    There is lot of working solutions i found in a search. I am listing few of them

    Sol Using Parse Exact


    DateTime dt = DateTime.ParseExact(dr["dateCreated"].ToString().Trim(), 
     "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
     
    //dr["dateCreated"] returns  date from database
     
     

    Sol Using TryParse

     
    DateTime date4;
    string dateString = @"20/05/2012";
    bool result = DateTime.TryParse(dateString,out date4); 
    
    
    the parsing fails, but it will not throw error, rather it returns  
    false indicating that the parsing failed.
     
     
    
    

    Sol Using appropriate culture (I got this working)

    string dateString = @"20/05/2012";
    DateTime date2 = Convert.ToDateTime(dateString,
     System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);

     

    
    
     
    
    
  • Copyright @ 2013 Code Snippets.