tags:

views:

303

answers:

3

This is what I have so far.

/// <summary>
/// Gets the date.
/// </summary>
/// <param name="date">The date: 05/07/2009</param>
/// <returns></returns>
private static DateTime GetDate(string date)
{
    DateTime postDate = DateTime.Parse(date);
    postDate.AddHours(DateTime.UtcNow.Hour);
    postDate.AddMinutes(DateTime.UtcNow.Minute);
    postDate.AddSeconds(DateTime.UtcNow.Second);
    postDate.AddMilliseconds(DateTime.UtcNow.Millisecond);

    return postDate;
}

Is there a better way to merge two dates? I'm looking for a more elegant solution.

+4  A: 

You can try this

/// <summary>
/// Gets the date.
/// </summary>
/// <param name="date">The date: 05/07/2009</param>
/// <returns></returns>
private static DateTime GetDate(string date)
{
    DateTime postDate = DateTime.Parse(date);        
    return postDate.Add(DateTime.UtcNow.TimeOfDay);        
}

MSDN Link: DateTime.Add

EDIT : Code change

Prashant
This answer is incorrect. DateTime is an immutable struct; the Add method does not modify the DateTime, but instead returns a new one!
Joren
@Joren: You are right, thank you for correcting me. :)
Prashant
This is incorrect. I've confirmed it.
Chuck Conway
Yes, this is now a correct solution.
Joren
+2  A: 

return DateTime.Parse(date) + DateTime.UtcNow.TimeOfDay;

JDunkerley
This is the correct answer.
Chuck Conway
A: 

I'm not sure how adding 2 dates makes any sense. Could you give an example how yesterday + now = something? Adding a TimeSpan would make sense: Yesterday + 1 day = today.

Could you explain exactly what you want? The date you parse is actually a TimeSpan? Then you should do:

return DateTime.UtcNow.Add(TimeSpan.parse(timespanstring))

Wouter