Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear All,

while parsing the string as DateTime in C#, the Following Exception Occurred for the Following string format.
string pstrDepartureDateTime = "2012-03-27T6:30";
suppose if the string format is in yyyy-MM-ddTHH:mm (i.e)
string pstrDepartureDateTime = "2012-03-27T06:30"; means parsing and the datetime conversion is working fine.

pls give solution.

Thanks,
lenin
Posted
Comments
ProEnggSoft 27-Mar-12 7:51am    
Please see my solution (2)to check whether it meets your requirement.

One option is to bring the Date string into the standard format Date string and then to use DateTime.ParseExact method

C#
static void Main(string[] args) {
    string datePattern = @"(\d{4})-(\d{1,2})-(\d{1,2})T(\d{1,2}):(\d{1,2})";
    string dateString = "2012-3-27T6:30";
    Match dateMatch = Regex.Match(dateString, datePattern);
    string spacers = "00--T:";
    if (dateMatch.Success && dateMatch.Groups.Count==6) {
        string formattedDateString = dateMatch.Groups[1].Value;
        for (int i = 2; i < dateMatch.Groups.Count; i++) {
            formattedDateString += spacers[i] + dateMatch.Groups[i].Value.PadLeft(2, '0');
        }
 
	var dt = new DateTime(int.Parse(dateMatch.Groups[1].Value),
	    int.Parse(dateMatch.Groups[2].Value),
	    int.Parse(dateMatch.Groups[3].Value),
	    int.Parse(dateMatch.Groups[4].Value),
	    int.Parse(dateMatch.Groups[5].Value), 0);
	 Console.WriteLine(formattedDateString);
	 Console.Write(dt);
	 Console.ReadKey();
    }
}
 
Share this answer
 
v2
Comments
ProEnggSoft 26-Mar-12 12:03pm    
Thank you Clifford Nelson for up voting.
You might also look at http://msdn.microsoft.com/en-us/library/5hh873ya.aspx[^]. there is a DateTime.TryParseExact that may be even easier and faster.
 
Share this answer
 
Not sure what the question is, but try using DateTime.TryParse to ensure[^] if the value is a date time or not.
 
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