Search code examples
c#.netdatetimeappendliterals

How to append time part of DateTime literal to a DateTime variable?


My project is of .net 3.5. I have a DateTime variable dt1 containing only Date part.

Now I want to append time part of DateTime literal # 13:45:39 # to dt1 and assign to a new DateTime variable dt2.

Anyone know how to do?

DateTime dt1 = #2016/12/31# ;
DateTime dt2 = /*code to append # 13:45:39 # to dt1 */  ;

Solution

  • My project is of .net 3.5. I have a DateTime variable dt1 containing only Date part

    DateTime is a struct in .NET Framework. It always has date and time parts. By this sentence, I assume your time part is 00:00:00 like;

    DateTime dt1 = new DateTime(2016, 12, 31);
    

    I want to append time part of DateTime literal # 13:45:39 # to dt1 and assign to a new DateTime variable dt2

    It is not clear what this literal means in that sentence but if you have a TimeSpan as 13:45:39, you can clearly add this value to your dt1 with DateTime.Add(TimeSpan) method like;

    TimeSpan ts = new TimeSpan(13, 45, 39);
    dt1 = dt1.Add(ts);
    

    If this # 13:45:39 # is a string, you can parse it to TimeSpan with ParseExact method first then use this Add method again like;

    TimeSpan ts = TimeSpan.ParseExact("# 13:45:39 #", "'# 'hh\\:mm\\:ss' #'", 
                                      CultureInfo.InvariantCulture);
    dt1 = dt1.Add(ts);