Click here to Skip to main content
15,913,758 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When i Try to convert string to datetime, it thrown an error & it says that "
C#
String was not recognized as a valid DateTime.

"

My code is give below

C#
string dateString = "16.10.2014";
DateTime formattedDate = DateTime.Parse(dateString);


Please have look into this code & give me the best way to solve it
Posted

C#
Use DateTime.ParseExact.

this.Text="16/10/2014";

DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);
 
Share this answer
 
You need to use existing CultureInfo, DateTimeFormat, settings here, or create custom ones: in this case you can use the "de-DE," "German" settings:
C#
using System.Globalization;

namespace YourNameSpace
{
    private static CultureInfo deCulInfo = new CultureInfo("de-DE"); 
    private static DateTimeFormatInfo deForInfo = deCulInfo.DateTimeFormat;
    private static DateTimeStyles dtStyle = DateTimeStyles.None;
    
        public string DateToDeString(DateTime dt)
        {
            return dt.ToString("dd'.'MM'.'yyyy", deCulInfo);
        }

        public DateTime DeStringToDate(string dts)
        {
           DateTime dt;

           if(DateTime.TryParse(dts, deForInfo, dtStyle, out dt)) return dt;

           return DateTime.MinValue;
        }
}

// test in some Method or EventHandler
// DateTime dt1 = new DateTime(2014,10,16);

// string txt = DateToDeString(dt1);

// DateTime dt2 = DeStringToDate(txt);

// set a break-point here and inspect values
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900