Join Date and Time to DateTime in C#

后端 未结 8 818
孤城傲影
孤城傲影 2020-12-25 09:46

I am retrieving data from an iSeries where there is a separate date and time fields. I want to join them into a DateTime field in my C# project. I don\'t see a way to add ju

相关标签:
8条回答
  • 2020-12-25 10:03

    You can do this quite easily:

    DateTime dateOnly;
    DateTime timeOnly;
    ...
    DateTime combined = dateOnly.Date.Add(timeOnly.TimeOfDay);
    

    TimeOfDay returns a TimeSpan, which you then add to the date.

    Edit (thanks to commenters below) - to be safe, use dateOnly.Date to ensure the date part only.

    0 讨论(0)
  • 2020-12-25 10:05
    Datetime date = new DateTime(Date1.Year, Date1.Month, Date1.Day, Time1.Hour, Time1.Minute, Time1.Second); 
    
    0 讨论(0)
  • 2020-12-25 10:10

    Note that adding the time to the date is not your biggest problem here. As @Reed Copsey mentioned, you just create a DateTime from the date and then .Add the time.

    However, you need to make sure that the iSeries date and time (a Unix time most probably) are in the same representation as the .Net representation. Thus, you most probably need to convert it by adding it to a Jan 1, 1970 DateTime as well.

    0 讨论(0)
  • 2020-12-25 10:15

    You could easily construct a TimeSpan from your "time" field.

    Once you have that, just do:

    TimeSpan time = GetTimeFieldData();
    dateField = dateField.Add(time);
    
    0 讨论(0)
  • 2020-12-25 10:17

    This should do:

    var output = date.Date + time.TimeOfDay;
    

    or

    var output = new DateTime(date.Year, date.Month, date.Day,
                              time.Hour, time.Minute, time.Second);
    

    suppose that both variable date and time are both of Type DateTime

    0 讨论(0)
  • 2020-12-25 10:19

    How are they being stored? Assuming that the date portion is being stored as a DateTime of midnight of the day in question and the time is a TimeSpan, you can just add them.

    DateTime date = ...;
    TimeSpan time = ...;
    
    DateTime result = date + time;
    
    0 讨论(0)
提交回复
热议问题