Thahleel al-Aleem
Thahleel al-Aleem

Reputation: 771

TimeSpan not calculating

I am trying to calculate create a time remaining calculator in VB.NET and it won't let me and I can't seem to figure out why. Here is my code

    Dim PrefendinedDateTime As DateTime = "3:00:00"
    Dim TimeNow As DateTime = DateTime.Now
    Dim ElapsedTime As TimeSpan = (TimeNow - frmStartDateTime)

    Dim TimeRemaining As TimeSpan = PrefendinedDateTime - New DateTime(ElapsedTime.Ticks)

    txtTimeRemaining.Text = New DateTime(TimeRemaining.Ticks).ToString("HH:mm:ss")

I get this error message:

Ticks must be between DateTime.MinValue.Ticks and DateTime.MaxValue.Ticks. Parameter name: ticks

Not quite sure what this means

Upvotes: 1

Views: 98

Answers (1)

Victor Zakharov
Victor Zakharov

Reputation: 26424

You cannot cast a timespan to a date, because those are different ticks. What you need is this:

txtTimeRemaining.Text = TimeRemaining.ToString("g")

or this:

txtTimeRemaining.Text = TimeRemaining.ToString("hh\:mm\:ss")

Notice how format string is different for TimeSpan, compared to formatting a date time, for example, and that : now requires escaping. This is explained in detail in below link #2.

References:

Let's stop here for a second, while I try to explain why it did not work for you. Forget about ticks, think in seconds, because it's a measurable interval, that's easy to get a grasp on. Suppose you time interval is a second. Now you are trying to create a date, passing one second into it. What do you expect to get? 1 second AD, i.e. 1st year, 1st month etc.? Fair enough.

Suppose now you have an interval of minus 1 second (yes, intervals can be negative). You would think it's 1 second BC, right? Unfortunately, negative dates in .NET are not allowed.

As a general rule of thumb, intervals of time (represented in .NET by a TimeSpan), and points in time (represented by a DateTime) should be treated separately, because they are logically different entities. There is one-way relation though, i.e. two dates can represent a TimeSpan. However, a TimeSpan does not represent two dates. In fact, no matter how many TimeSpans you have, you will never be able to relate them to any point in time.

Upvotes: 1

Related Questions