代码之家  ›  专栏  ›  技术社区  ›  user1702369

仅将时间跨度添加到日期时间,而不是日期时间

  •  -2
  • user1702369  · 技术社区  · 8 年前

    我有两个日期时间:

    DateTime beginDate = 2000/01/01 14:00
    
    DateTime endDate =  2000/01/01 14:30
    

    TimeSpan span = endDate.Subtract(beginDate);
    var myValue = beginDate.AddMinutes( span.Minutes ).TimeOfDay.Ticks
    
    //Trying to get this equal to the endDate by using the beginDate + myValue
    //I have to use myvalue, because this value comes from the DB and this piece 
    //of code sits in another class than the above code
    DateTime otherDate = beginDate.Date.Add( new TimeSpan( myValue ) )
    

    问题是我一直在0:30回来,我应该14:30回来。 我明白为什么,这是因为开始。日期为2000/01/01 00:00,但我不能使用beginDate。一天的时间。添加,因为它是一个只读字段。 我该如何实现它只会将myValue添加到给定日期的时间??

    2 回复  |  直到 8 年前
        1
  •  2
  •   ispiro    8 年前

    你应该使用 TimeSpan.TotalMinutes .

    span.Minutes 只给你分钟的部分。第页,共页 1:30 不会是90岁。会的 30 . 使用 TotalMinutes 90 .

    beginDate.Date 应更改为 beginDate Date 您正在删除时间。

        2
  •  1
  •   Derek    8 年前
    DateTime otherDate = beginDate + span;