Date and time arithmetics

One of our developer wrote this code

private DateTimeOffset CombineAppointmentDateTime(string date, string time)
{
    time = time == "NA" ? "00:00" : (time == "9:30" ? "09:30" : time);
    var dateTime = DateTime.ParseExact($"{date} {time}", 
                       Constants.DateTimeFormat, CultureInfo.InvariantCulture);
    return DateTime.SpecifyKind(dateTime, DateTimeKind.Local);
}

var result = CombineAppointmentDateTime(
    DateTime.Now.ToString("yyyy-MM-dd"), "13:00");

He is combining the date and time but in a clumsy way. What he’s doing is composing a string then convert it to DateTime. A lot of junior developers do this way for some reasons.

What a lot of developers tend to forget is that using date and time arithmetics is much more effiencient and readable.

The code below is much better.

private DateTimeOffset CombineAppointmentDateTime(DateTime date, string time)
{
    return TimeSpan.TryParse(time, out TimeSpan val)
           ? date.Date + val
           : date.Date;
}

var result = CombineAppointmentDateTime(DateTime.Now,"13:00");