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.
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.
var dateValue = new Date("2021-01-12 10:10:20"); Use new Date() along with setHours() and getHours() to add time.
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.
You can use TimeSpan.Parse to parse the time, and then add the result to the date:
DateTime newDateTime = oldDateTime.Add(TimeSpan.Parse(timeString));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With