Difference between two Date objects...including times... RRS feed

  • Question

  • Let's say I am trying to compare the difference in time between the exact time & date now, and noon tomorrow, or noon on Christmas day 2014...

    I thought maybe I initialize a DateTime object for DateTime.Now and another for the future date...then subtract the future date from now, and I can see how long is between the 2 in days, hours, minutes, and seconds...and display that info...but it doesn't seem to work...how can I do something like this...basically I want to create a countdown till a certain event starts...and after it starts recognize as much & display a message saying as much...how would I do this?

    The main part is trying to find the difference in the times/dates so I can display the correct days,hours,minutes, and seconds...until said event starts, after I can do that, I could handle the rest...

    My language of choice by the way is VB for this particular app...

    Tuesday, August 13, 2013 3:50 AM


All replies

  • You can use DateTime.Subtract DateTime.Now from your future DateTime to get the TimeSpan for the difference. What exactly did you do (what does your code look like) and in what way did it not work? What results did you expect, and what results did you get?

    See Performing Arithmetic Operations with Dates and Times for more details.


    • Marked as answer by Maya Key Tuesday, August 13, 2013 6:37 AM
    Tuesday, August 13, 2013 6:27 AM
  • OK so it was working as it should all along...my problem was actually that I was silly and forgetful...I passed params from one page to the next, then to my own class in a new() constructor, and lots of other things, and at one location I failed to pass the variable I should have with the actual DateTime object in it, instead it was passing a blank DateTime, and thus leaving me with a value ending up being DateTime.Now but as the negative value of it.

    Sorry, I am a bit tired, it took me till just now when you said it should work for me to find my mistake after doing a generic test with a new project & seeing it actually worked fine how I was doing it...

    • Edited by Maya Key Tuesday, August 13, 2013 6:38 AM
    Tuesday, August 13, 2013 6:37 AM
  • TimeSpan difference = new DateTime(2014, 12, 24, 12, 0, 0) - DateTime.Now;
    string timeLeft = string.Format("Santa swings by in : {0}", difference);

    twitter: http://www.twitter.com/dotMorten
    blog: http://www.sharpgis.net

    Sunday, August 18, 2013 5:26 AM