Reputation: 34008
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);
Upvotes: 0
Views: 843
Reputation: 1501153
EDIT: Looking at it again, I strongly suspect you don't need to do any parsing at all. I suspect you could use:
DateTime date = ((DateTime) dr[1]).Date;
TimeSpan time = ((DateTime) dr[3]).TimeOfDay;
DateTime combined = date + time;
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 DateTime
for you) I suggest using DateTime.ParseExact
for both parts:
dd/MM/yyyy
dd/MM/yyyy hh:mm tt
I'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:
DateTime combined = date.Date + time.TimeOfDay;
Alternatively, you could use my Noda Time library, which has separate LocalDate
and LocalTime
concepts, which can be combined easily into a LocalDateTime
...
Upvotes: 1
Reputation: 16714
Try DateTime.ParseExact
method:
string date = dr[1].ToString();
string time = dr[3].ToString();
time = time.Substring(time.IndexOf(' ') + 1);
DateTime.ParseExact(string.Format("{0} {1}", date, time), "dd/MM/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);
Upvotes: 1
Reputation: 82096
I would suggest using DateTime.ParseExact so you can specifically say which parts of the dates you need e.g.
var date = DateTime.ParseExact(dr[1], "dd/MM/yyyy", CurrentCulture.InvariantCulture).Date;
var time = DateTime.ParseExact(dr[3], "HH:mm", CurrentCulture.InvariantCulture).TimeOfDay;
var eventDate = date + time;
Upvotes: 1