简体   繁体   中英

Join 1 date string + 1 time string and convert to datetime

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);

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);

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:

  • For the first part, use a format of dd/MM/yyyy
  • For the second part, use a format of 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 ...

I would suggest using DateTime.ParseExact so you can specifically say which parts of the dates you need eg

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM