Click here to Skip to main content
15,891,567 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
DateTime.ParseExact(value[54].Trim(), "d/M/yyyy", CultureInfo.InvariantCulture);



the code fails when date in the format dd/mm/yyyy is given instead of date time.

Any one faced this issue before?

What I have tried:

C#
DateTime.ParseExact(value[54].Trim(), "d/M/yyyy", CultureInfo.InvariantCulture);
Posted

You date format string is not accurate. Take a look at this[^] page for format strings.

In order to cater for multiple date formats, you should go for TryParseExact. It accepts an array of strings for different formats.
 
Share this answer
 
v2
Comments
spriyanair 16-Feb-16 2:15am    
DateTime.ParseExact(value[21].Trim(), "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture); I have used this code before its working fine if string is date time.But it fails when date alone is given.Could you clarify with an example
dan!sh 16-Feb-16 2:18am    
Do not provide HH:mm:ss if it is not in the string value.
spriyanair 16-Feb-16 2:20am    
some data have time stamp some don't have; have to work in both the cases
dan!sh 16-Feb-16 3:40am    
Updated the response.
Use 'ParseExact' method of 'DateTime' class with 'dd/MM/yyyy' format, it also work for 'd/M/yyyy'.
see below snippet
C#
string dt = "24/12/2010";
DateTime dt1;
//always use InvariantCulture for dateformat provider as it support large number of customized datetime formats
System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
dt1 = DateTime.ParseExact(dt, "dd/MM/yyyy", provider);
MessageBox.Show("String successfully converted to DateTime" + dt1.Year);  


Hope it helps
for more detail see this[^]
 
Share this answer
 
Comments
spriyanair 16-Feb-16 2:54am    
what happens if string is in date time format
koolprasad2003 16-Feb-16 3:49am    
Just convert the format to hh:MM:ss
dt1 = DateTime.ParseExact(dt, "dd/MM/yyyy hh:MM:ss", provider);
spriyanair 16-Feb-16 3:59am    
I id like that only it work fine when date with time stamp is given but will fails when date alone is given
koolprasad2003 16-Feb-16 4:06am    
what error you faced ? exception message ?
As suggested, use TryParseExact and pass it a list of formats you accept, then add some code that handles when the string isn't in a format you accept.

DateTime.TryParseExact Method (String, String[], IFormatProvider, DateTimeStyles, DateTime) (System)[^]
 
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