tags:

views:

48

answers:

4

I am working with an old mysql database in which a date is stored (without a time) as a datetime and a time is stored as a string (without a date).

In C# I then have a DateTime with a value like 2010-06-25 12:00:00 AM and a String with a value like 15:02.

What is the most concise way to combine these without a lot of overhead?

I have tried a few methods including:

DateTime NewDateTime = DateTime.Parse(OldDateTime.ToString("yyyy-MM-dd ") + TimeString);

I dislike converting the existing DateTime to a string and appending the time.

I can convert the time string to a date, but then I get today's date and adding it as a number of ticks to the old datetime is incorrect.

Note: Don't worry about validation, it is done elsewhere. The time is represented using 24-hour format without seconds.

+3  A: 

You can use TimeSpan.Parse to parse the time, and then add the result to the date:

DateTime newDateTime = oldDateTime.Add(TimeSpan.Parse(timeString));
dtb
@dtb, good solution. @JYelton, I'd use this and mark dtb's answer correct.
Brian Scott
I can't believe I forgot about using `TimeSpan` - this is precisely what was needed.
JYelton
A: 

I think you're worrying about the string conversion too much. By combining the 2 string elements together you are saving further date string parsing anyway which will most likely be more expensive.

Is this going to be repeated a lot of times or a simple step in a larger process?

Brian Scott
+1  A: 
var dt = new DateTime(2010, 06, 26); // time is zero by default
var tm = TimeSpan.Parse("01:16:50");
var fullDt = dt + tm; // 2010-06-26 01:16:50
simendsjo
A: 

I am fairly sure you could combine and convert these values into a timestamp using SQL.

daedalus0x1a4
Hitting the database for such things is a really bad idea. Your program will be a lot slower, and suddenly have strong external dependencies without any good reason.
simendsjo
I figured the SQL would be faster than the C# but I haven't read much about it. Thanks for the infosss.
daedalus0x1a4