I have just come across this post because I had a similar issue whereby I wanted to set the time for an Entity Framework object in MVC that gets the date from a view (datepicker) so the time component is 00:00:00 but I need it to be the current time. Based on the answers in this post I came up with:
If you already have the time stored in another DateTime object you can use the Add method.
DateTime dateToUse = DateTime.Now();
DateTime timeToUse = new DateTime(2012, 2, 4, 10, 15, 30); //10:15:30 AM
DateTime dateWithRightTime = dateToUse.Date.Add(timeToUse.TimeOfDay);
The TimeOfDay property is a TimeSpan object and can be passed to the Add method. And since we use the Date property of the dateToUse variable we get just the date and add the time span.
Happened upon this post as I was looking for the same functionality this could possibly do what the guy wanted. Take the original date and replace the time part
Executed: Today = 9/04/15 00:00:00
I have just come across this post because I had a similar issue whereby I wanted to set the time for an Entity Framework object in MVC that gets the date from a view (datepicker) so the time component is 00:00:00 but I need it to be the current time. Based on the answers in this post I came up with:
If you already have the time stored in another
DateTime
object you can use theAdd
method.The
TimeOfDay
property is aTimeSpan
object and can be passed to theAdd
method. And since we use theDate
property of thedateToUse
variable we get just the date and add the time span.Try this one
Simplest solution :
And if you need a specific Date and Time Format :
Happened upon this post as I was looking for the same functionality this could possibly do what the guy wanted. Take the original date and replace the time part