46

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.

5 Answers 5

82

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

DateTime newDateTime = oldDateTime.Add(TimeSpan.Parse(timeString));
2
  • good solution. @JYelton, I'd use this and mark dtb's answer correct. Jun 25, 2010 at 23:18
  • I can't believe I forgot about using TimeSpan - this is precisely what was needed.
    – JYelton
    Jun 25, 2010 at 23:26
12
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
6

I used something similar to what simendsjo says, except I continued to have it as a DateTime

DateTime date = Convert.ToDateTime(txtTrainDate.Text);
DateTime time = Convert.ToDateTime(ddTrainTime.SelectedValue);
DateTime dtCOMPLTDTTM = new DateTime(date.Year, date.Month, date.Day, time.Hour, time.Minute, time.Second);
1
  • Good for when you want to combine the "time" part of one DateTime value and the "date" part of another DateTime value. Jul 27, 2016 at 19:26
0

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?

0

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

1
  • 3
    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
    Jun 26, 2010 at 9:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.