Chuck Conway
Chuck Conway

Reputation: 16435

Merge Two DateTime types in C#

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.

Upvotes: 2

Views: 3619

Answers (3)

JDunkerley
JDunkerley

Reputation: 12505

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

Upvotes: 3

Wouter
Wouter

Reputation: 2262

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))

Upvotes: 1

Prashant Cholachagudda
Prashant Cholachagudda

Reputation: 13092

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

Upvotes: 7

Related Questions