Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine date and time when date is a DateTime and time is a string

Tags:

c#

datetime

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.

like image 678
JYelton Avatar asked Jun 25 '10 23:06

JYelton


People also ask

How do I concatenate date and time to text in Excel?

Enter this formula: =concatenate(text(A2,"mm/dd/yyyy")&" "&text(B2,"hh:mm:ss")) into a blank cell where you want to put the combined result, then press Enter key to get the first combined cell.

How do you add date and time to string?

var dateValue = new Date("2021-01-12 10:10:20"); Use new Date() along with setHours() and getHours() to add time.

Is datetime date a string?

The program below converts a datetime object containing current date and time to different string formats. Here, year , day , time and date_time are strings, whereas now is a datetime object.


2 Answers

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

DateTime newDateTime = oldDateTime.Add(TimeSpan.Parse(timeString)); 
like image 132
dtb Avatar answered Sep 19 '22 18:09

dtb


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 
like image 29
simendsjo Avatar answered Sep 19 '22 18:09

simendsjo