Eggybread
Eggybread

Reputation: 359

Countdown timer needs some rounding down ? VB / Asp.Net

I had this written for me.. It counts down to our next sale but the minutes don't change until the second drop to under 30. The hours don't change till the minutes drop to under 30 etc. I posted this some time ago but solution supplied was beyond me. I just wondered if anyone knew a way if the current code could be tweaked to work ?

    Dim seconds As Integer = DateDiff(DateInterval.Second, Date.Now, BootSale.nextDOW(DayOfWeek.Sunday))
    Dim days, hours, minutes As Integer
    days = seconds / 86400
    hours = (seconds Mod 86400) / 3600
    minutes = (seconds Mod 3600) / 60
    lblTimer.Text = days & " Day(s) " & hours & " Hour(s) " & minutes & " Minute(s) " ' & seconds Mod 60 & " Seconds"

Upvotes: 0

Views: 214

Answers (2)

FloatingKiwi
FloatingKiwi

Reputation: 4506

.Net is rounding these automatically as you don't have option strict on. You can use Math.Floor to always round down.

Dim seconds As Integer = DateDiff(DateInterval.Second, Date.Now, BootSale.nextDOW(DayOfWeek.Sunday))
Dim days, hours, minutes As Integer
days = Math.Floor(seconds / 86400)
hours = Math.Floor((seconds Mod 86400) / 3600)
minutes = Math.Floor((seconds Mod 3600) / 60)
lblTimer.Text = days & " Day(s) " & hours & " Hour(s) " & minutes & " Minute(s) " ' & seconds Mod 60 & " Seconds"

I've rewritten it as a function so you can see my test cases are working.

Public Function TestDate(d1 As DateTime, d2 As DateTime) As String
    Dim seconds As Integer = DateDiff(DateInterval.Second, d1, d2)
    Dim days, hours, minutes As Integer
    days = Math.Floor(seconds / 86400)
    hours = Math.Floor((seconds Mod 86400) / 3600)
    minutes = Math.Floor((seconds Mod 3600) / 60)
    Return days & " Day(s) " & hours & " Hour(s) " & minutes & " Minute(s) "
End Function

Assert.AreEqual("2 Day(s) 15 Hour(s) 45 Minute(s) ", TestDate(n, n.Add(New TimeSpan(2, 15, 45, 45))))
Assert.AreEqual("2 Day(s) 5 Hour(s) 5 Minute(s) ", TestDate(n, n.Add(New TimeSpan(2, 5, 5, 5))))

Upvotes: 0

the_lotus
the_lotus

Reputation: 12748

You should use proper .NET functions to do that. The TimeSpan structure already have the functionality that you need.

    Dim difference As TimeSpan = BootSale.nextDOW(DayOfWeek.Sunday).Subtract(DateTime.Now)

    Dim message As String = String.Format("{0} Day(s) {1} Hour(s) {2} Minute(s)", difference.Days, difference.Hours, difference.Minutes)

    lblTimer.Text = message

Upvotes: 1

Related Questions