The date...">

Merging 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 combine the two dates? I am looking for a more elegant solution.

+2


source to share


3 answers


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

      



+3


source


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

+7


source


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

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

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

+1


source







All Articles