Iam reading from an excel file 2 columns:
One column has value:
07/11/2012
2nd column has value:
18:45
When I read the 2nd column, it shows actually a default date in front of it.
dr[3].ToString() “30/12/1899 6:45:00 PM” string
I want to join the first column with the second. but right now I have the normal input format exception
I tried to remove the date part from the second column with string manipulation
here is my code
DateTime dateEvent = DateTime.Parse(dr[1].ToString());
dateEvent.Add(TimeSpan.Parse(dr[3].ToString().Substring(dr[3].ToString().IndexOf(" ")+1)));
Udpate 1:
DateTime dateEvent = DateTime.ParseExact(string.Format("{0} {1}", dr[1].ToString(), dr[3].ToString().IndexOf(" ") + 1), "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture);
EDIT: Looking at it again, I strongly suspect you don’t need to do any parsing at all. I suspect you could use:
You shouldn’t just blindly call
ToString()on values, without understanding what the type is: often it’s exactly the right type, and you can save yourself a potentially-lossy string conversion.Assuming you have to parse (rather than getting Excel to convert to a
DateTimefor you) I suggest usingDateTime.ParseExactfor both parts:dd/MM/yyyydd/MM/yyyy hh:mm ttI’d suggest using the invariant culture explicitly – assuming you really know that this format is completely fixed. (If you don’t, that’s a bigger problem.)
Then join them together like this:
Alternatively, you could use my Noda Time library, which has separate
LocalDateandLocalTimeconcepts, which can be combined easily into aLocalDateTime…