How to subtract a datetime from another datetime?

后端 未结 7 894
借酒劲吻你
借酒劲吻你 2020-12-03 20:36

How do I subtract two DateTime values from another DateTime value and have the result saved to a double?

相关标签:
7条回答
  • 2020-12-03 21:08

    In .NET, if you subtract one DateTime object from another, you will get a TimeSpan object. You can then use the Ticks property on that TimeSpan object to get the number of ticks between the two DateTime objects. However, the ticks will be represented by a Long, not a Double.

    DateTime date1;
    DateTime date2;
    Long diffTicks = (date2 - date1).Ticks;
    

    There are other interesting properties on the TimeSpan object like TotalMilliseconds and TotalMinutes and things like that which can help you out, and may be more what you are looking for.

    0 讨论(0)
  • 2020-12-03 21:15

    You should try in this.

    DateTime prevDate = DateTime.Parse("25-Feb-2011 12:30");
    double subDouble = DateTime.Now.Ticks - prevDate.Ticks;
    
    0 讨论(0)
  • 2020-12-03 21:22

    Use DateTime.Subtract which will return TimeSpan , then use TotalSeconds property of the result which is of type double.

    0 讨论(0)
  • 2020-12-03 21:25

    I think this is what you need.

    DateTime d1 = DateTime.Now;
    DateTime d2 = DateTime.UtcNow;
    
    var result = d1 - d2;
    
    double dResult = result.Ticks;
    
    0 讨论(0)
  • 2020-12-03 21:28
    DateTime startTime = DateTime.Now; 
    DateTime endTime = DateTime.Now.AddSeconds( 75 );  
    TimeSpan span = endTime.Subtract ( startTime ); 
    Console.WriteLine( "Time Difference (seconds): " + span.Seconds ); 
    Console.WriteLine( "Time Difference (minutes): " + span.Minutes ); 
    Console.WriteLine( "Time Difference (hours): " + span.Hours ); 
    Console.WriteLine( "Time Difference (days): " + span.Days );
    
    0 讨论(0)
  • 2020-12-03 21:30

    I am not sure what is you want to store if you need a double

      double difference = date2.ToOADate() - date1.ToOADate();
    
    0 讨论(0)
提交回复
热议问题